【问题标题】:"Read-only" public properties without setters/getters没有设置器/获取器的“只读”公共属性
【发布时间】:2015-01-05 14:24:13
【问题描述】:

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

【问题讨论】:

  • 是的。您可以使用getset 之一或两者定义属性,并带有支持字段。但是,这并不能阻止您在类内获得支持字段。自 C# 6 起,这已扩展到自动属性,向后 C# 5 中的自动属性始终能够更改 getter 或 setter 的可访问性,但不能省略其中之一。
  • 太好了,谢谢亚当! (:

标签: c# oop properties readonly


【解决方案1】:

可以,语法是这样的:

public int AProperty { get; private set; }

【讨论】:

    【解决方案2】:

    是的。您可以将只读属性与私有设置器一起使用。

    Using Properties - msdn

        public string Name    
        {
            get;
            private set;
        }
    

    【讨论】:

      猜你喜欢
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 2014-07-24
      相关资源
      最近更新 更多