没有setter / getters的“只读”公共属性

时间:2015-01-05 14:24:13

标签: c# oop properties readonly

C#是否具有这样的功能(比如Python的getter-only模式)?

class A 
{
   public [read-only] Int32 A_;

   public A() 
   {
      this.A_ = new Int32();
   }

   public A method1(Int32 param1) 
   {
      this.A_ = param1;
      return this;
   }
}

class B 
{
   public B() 
   {
      A inst = new A().method1(123);
      Int32 number = A.A_; // okay
      A.A_ = 456;          // should throw a compiler exception
   }
}

为了获得这个,我可以在A_属性上使用private修饰符,并且只实现一个getter方法。这样做,为了访问该属性,我应该总是调用getter方法......是否可以避免?

2 个答案:

答案 0 :(得分:2)

是的,这是可能的,语法是这样的:

public int AProperty { get; private set; }

答案 1 :(得分:1)

是肯定的。您可以使用私有设置器的只读属性。

Using Properties - msdn

    public string Name    
    {
        get;
        private set;
    }