详解C#中的接口属性以及属性访问器的访问限制

2019-12-26 17:27:27丽君


public interface ISomeInterface
{
  int TestProperty
  {
    // No access modifier allowed here
    // because this is an interface.
    get;
  }
}

public class TestClass : ISomeInterface
{
  public int TestProperty
  {
    // Cannot use access modifier here because
    // this is an interface implementation.
    get { return 10; }

    // Interface property does not have set accessor,
    // so access modifier is allowed.
    protected set { }
  }
}

访问器可访问性域
如果对访问器使用访问某个修饰符,则访问器的可访问性域由该修饰符确定。
如果不对访问器使用访问修饰符,则访问器的可访问性域由属性或索引器的可访问性级别确定。
下面的示例包含三个类:BaseClass、DerivedClass 和 MainClass。每个类的 BaseClass、Name 和 Id 都有两个属性。该示例演示在使用限制性访问修饰符(如 protected 或 private)时,如何通过 BaseClass 的 Id 属性隐藏 DerivedClass 的 Id 属性。因此,向该属性赋值时,将调用 BaseClass 类中的属性。将访问修饰符替换为 public 将使该属性可访问。
该示例还演示 DerivedClass 的 Name 属性的 set 访问器上的限制性访问修饰符(如 private 或 protected)如何防止对该访问器的访问,并在向它赋值时生成错误。


public class BaseClass
{
  private string name = "Name-BaseClass";
  private string id = "ID-BaseClass";

  public string Name
  {
    get { return name; }
    set { }
  }

  public string Id
  {
    get { return id; }
    set { }
  }
}

public class DerivedClass : BaseClass
{
  private string name = "Name-DerivedClass";
  private string id = "ID-DerivedClass";

  new public string Name
  {
    get
    {
      return name;
    }

    // Using "protected" would make the set accessor not accessible. 
    set
    {
      name = value;
    }
  }

  // Using private on the following property hides it in the Main Class.
  // Any assignment to the property will use Id in BaseClass.
  new private string Id
  {
    get
    {
      return id;
    }
    set
    {
      id = value;
    }
  }
}

class MainClass
{
  static void Main()
  {
    BaseClass b1 = new BaseClass();
    DerivedClass d1 = new DerivedClass();

    b1.Name = "Mary";
    d1.Name = "John";

    b1.Id = "Mary123";
    d1.Id = "John123"; // The BaseClass.Id property is called.

    System.Console.WriteLine("Base: {0}, {1}", b1.Name, b1.Id);
    System.Console.WriteLine("Derived: {0}, {1}", d1.Name, d1.Id);

    // Keep the console window open in debug mode.
    System.Console.WriteLine("Press any key to exit.");
    System.Console.ReadKey();
  }
}

输出:


  Base: Name-BaseClass, ID-BaseClass
  Derived: John, ID-BaseClass