首页 > 代码库 > Property

Property

Interface Property

  Properties can be declared on an interface (C# Reference). 

  

  按如下形式实现interfac来避免冲突。

  

  在没有interface前缀的情况下,编译器不会报错,2个interface引用同一方法:  

class Test {    static void Main()    {        SampleClass sc = new SampleClass();        IControl ctrl = (IControl)sc;        ISurface srfc = (ISurface)sc;        // The following lines all call the same method.        sc.Paint();        ctrl.Paint();        srfc.Paint();    }}interface IControl{    void Paint();}interface ISurface{    void Paint();}class SampleClass : IControl, ISurface{    // Both ISurface.Paint and IControl.Paint call this method.     public void Paint()    {        Console.WriteLine("Paint method in SampleClass");    }}// Output:// Paint method in SampleClass// Paint method in SampleClass// Paint method in SampleClass
View Code

  为每个interface实现不同的方法可以按如下这样:

public class SampleClass : IControl, ISurface{    void IControl.Paint()    {        System.Console.WriteLine("IControl.Paint");    }    void ISurface.Paint()    {        System.Console.WriteLine("ISurface.Paint");    }}
View Code

 

  访问器可以为virtual,这也意味着可以override:

public class Parent{    public virtual int TestProperty    {        // Notice the accessor accessibility level.        protected set { }        // No access modifier is used here.        get { return 0; }    }}public class Kid : Parent{    public override int TestProperty    {        // Use the same accessibility level as in the overridden accessor.        protected set { }        // Cannot use access modifier here.        get { return 0; }    }}
View Code

 

参考:

1、http://msdn.microsoft.com/zh-cn/library/64syzecx.aspx

2、http://msdn.microsoft.com/zh-cn/library/ms173157.aspx

3、http://msdn.microsoft.com/zh-cn/library/75e8y5dd.aspx