【问题标题】:Class Property, Gettable and settable internally, but only gettable externally类属性,可在内部获取和设置,但只能在外部获取
【发布时间】:2013-04-10 11:05:46
【问题描述】:

我意识到这可能是非常基本的事情,但我不确定实现以下目标的最佳实践。

我有以下带有字符串属性myString的类:

public class MyClass
{
    public string myString
    {
        get {
            return myString;
        }
    }

    public void AFunction()
    {
        // Set the string within a function
        this.myString = "New Value"; // Error because the property is read-only
    }
}

我希望myString 属性符合以下条件:

  • 内部可设置
  • 内部可获取
  • 不可在外部设置
  • 可从外部获取

所以我希望能够在类内设置变量myString,并使其值在类外只读。

有没有办法在不使用单独的 get 和 set 函数并将 myString 属性设为私有的情况下实现这一点,如下所示:

public class MyClass
{
    private string myString { get; set; }

    public void SetString()
    {
        // Set string from within the class
        this.myString = "New Value";
    } 

    public string GetString()
    {
        // Return the string
        return this.myString;
    }
}

上面的示例允许我在内部设置变量,但不能从类外部对实际属性 myString 进行只读访问。

我尝试了protected,但这并不能从外部访问该值。

【问题讨论】:

    标签: c# class properties


    【解决方案1】:

    听起来你只是想要:

    public string MyString { get; private set; }
    

    这是一个具有公共 getter 和私有 setter 的属性。

    根本不需要额外的方法。

    (请注意,鉴于 C# 中关键字 internal 的具体含义,此处使用“内部”一词可能会造成混淆。)

    【讨论】:

      【解决方案2】:

      你可以只允许类成员的setter,通常是构造函数:

      public class MyClass
      {
          public string myString { get; private set; }
      }
      

      或者您可以在内部/装配成员中允许设置器:

      public class MyClass
      {
          public string myString { get; internal set; }
      }
      

      getter 将是公开的。

      【讨论】:

        【解决方案3】:

        你可以在get和set上指定访问修饰符,例如:

        public string MyString
        {
            get;
            private set;
        }
        

        【讨论】:

          【解决方案4】:
          public string myString { get; private set; }
          

          【讨论】:

          • 这将导致堆栈溢出,因为 get/set 只是一遍又一遍地调用自身。您需要让它访问一个不同命名的支持字段。
          • 我已经更新了 - 你没有刷新页面。起初并没有注意到@Coulton 代码中的原始错误
          • 抱歉时机不好! +1
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-10-06
          • 1970-01-01
          • 2020-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-01
          相关资源
          最近更新 更多