.NET重思(一)sealed和interface

博主这几天正好闲着,砸砸基础,毕竟自学,基础不牢靠很致命,要踏实啊~~~

1.sealed关键字修饰一个类,也可以修饰实现方法或者属性。当sealed用于修饰一个类时,这个类不可以被继承,因此,这个类也叫做密封类。相对应的,被abstract修饰的类称为抽象类,这个类必须继承才有意义。

class Program
    {
        static void Main(string[] args)
        {

        }
    }

    class Product
    {
        private string name;
        public virtual void display()
        {
            Console.WriteLine("这是product类
");
        }
    }

    sealed class Computer:Product
    {
        public Computer() { }
    }

    /// <summary>
    /// 将报错,因为继承的Computer为密封类
    /// </summary>
    //class Surface : Computer
    //{

    //}

    class Phone:Product
    {
        public Phone() { }

        public sealed override void display()
        {
            Console.WriteLine("这是Phone类的display,密封方法!");
        }
    }

    class WP:Phone
    {
        /// <summary>
        /// 将报错,因为继承的Phone类中display为密封方法,无法重写
        /// </summary>
        //public sealed override void display()
        //{

        //}
    }

Sealed修饰实例方法或属性,应该与override一起使用。

2.interface接口用于给使用者显示功能并使用,而不必知道其中的实现。当功能模块需要变更,程序狗只需要将该功能模块的实现代码进行修改,其他调用这个接口的程序将无需变动。接口的这种应用模式称之为Bridge模式,Bridge模式分离意图和实现,以得到更好的扩展性。

class Program
    {
        static void Main(string[] args)
        {
            Computer a = new PC();
            Console.WriteLine("这台电脑的CPU为:{0}",a.getCPU());
            Console.WriteLine("这台电脑的显卡为:{0}",a.Videocard);

            //报错,因为Computer接口的声明中Videocard为只读(没有set访问器)
            //a.Videocard = Console.ReadLine();

            PC b = new PC();
            //实例b可以写入Videocard属性
            b.Videocard = Console.ReadLine();
        }
    }

    interface Computer
    {
        string getCPU();
        string Videocard
        {
            get;
        }
    }

    class PC:Computer
    {
        private string _vc = "Nvidia";

        public string Videocard
        {
            get
            {
                return _vc;
            }
            set
            {
                _vc = value;
            }
        }

        public string getCPU()
        {
            return "Intel";
        }
    }

而且要补充一点,接口可以继承多个接口,但是类只能单继承。接口的访问权限是public,类或者结构实现接口的成员必须保持public,并且实现方法的签名必须和接口方法签名要一致。

原文地址:https://www.cnblogs.com/mengnan/p/4824081.html