码迷,mamicode.com
首页 > 其他好文 > 详细

抽象类与接口

时间:2017-06-04 19:52:28      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:this   tee   tor   重写   抽象方法   abs   方法重写   style   handler   

 

1. 抽象类用abstrac修饰, 如abstrac class E。

   抽象类里的抽象方法也用abstract修饰,如public abstract override void DoWork(int i);

   非抽象类里不能有抽象方法。

   抽象类里可由数据成员,可以实现方法。

   当抽象类从基类继承虚方法时,抽象类可以使用抽象方法重写该虚方法。如public abstract override void DoWork(int i);

        public class D
        {
            public virtual void DoWork(int i)
            {
                // Original implementation.
            }
        }

        public abstract class E : D
        {
            public abstract override void DoWork(int i);

            public abstract void Open();

            public void NormalFoo()
            {
                this.i = 10;
                this.name = "Lucy";
                Console.WriteLine("no virtual, no abstract function.{0}, {1}", this.i, this.name);
            }

            private int i;
            private string name;
        }

        public class F : E
        {
            public override void DoWork(int i)
            {
                // New implementation.
            }

            public override void Open()
            {
                throw new NotImplementedException();
            }
        }

 

接口只能包括方法,属性、索引器、事件,

        interface IInterface
        {
            void Test();
            string this[int id] { get; }
            string Name { get; set; }
            event CompeleteEventHandler WorkCompleted;
        }

        class MyClass3 : IInterface
        {
            public void Test() 
            {
                this.WorkCompleted();
            }

            public string this[int id] { get { return ""; } }
            public string Name { get{return "";} set{} }

            public event CompeleteEventHandler WorkCompleted;
        }

 

相同与区别:

都不能实例化。

接口表达的是行为的规范和契约,代表的是一种能做某事能力。IEnumerable,IEnumerator, ICloneable,

抽象类通常定义在关系密切的类层次之中,处于较上位置,一个类一次可以实现若干个接口,但是只能扩展一个父类 。

而接口大多数是处于关系疏松但都实现某一功能的类中.

抽象类)定义了你是什么,接口(锁)规定了你能做什么。

 

抽象类与接口

标签:this   tee   tor   重写   抽象方法   abs   方法重写   style   handler   

原文地址:http://www.cnblogs.com/dirichlet/p/3317996.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!