繁体   English   中英

没有设置器/获取器的“只读”公共属性

[英]“Read-only” public properties without setters/getters

C#是否具有这样的功能(例如Python的仅吸气剂模式)?

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方法...可以避免吗?

是的,这是可能的,语法如下:

public int AProperty { get; private set; }

是。 您可以对私有设置程序使用只读属性。

使用属性-msdn

    public string Name    
    {
        get;
        private set;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM