【问题标题】:Replacing Property Value with only a get?仅用获取替换属性值?
【发布时间】:2020-09-14 17:25:12
【问题描述】:

快速提问:

是否可以在没有设置器的情况下更改“MyProperty”的值?

public static void MyClass
{
    private readonly string myProperty;

    public MyClass(string property)
    {
        this.myProperty = property;
    }

    public static string MyProperty {get {return this.myProperty}}
}

【问题讨论】:

    标签: c# .net visual-studio properties


    【解决方案1】:

    您还可以拥有一个私有值并使用一种方法来设置该值。如果你打算使用这种方法,你最好去掉静电。

    void Main()
    {
        SetValue("New Value");
    }
    
    private static string _propertyValue { get; set; }
    
    public static string MyProperty
    {
        get
        {
            return _propertyValue;
        }
    }
    
    public static void SetValue(string value)
    {
        _propertyValue = value;
    }
    

    【讨论】:

      【解决方案2】:

      每个 AppDomain 仅一次,通过静态构造函数:

      public static class MyClass
      {
          public static string MyProperty { get; }
      
          static MyClass()
          {
              MyProperty = "SomeValue";
          }
      }
      

      或通过初始化程序:

      public static class MyClass
      {
          public static string MyProperty { get; } = "SomeValue";
      }
      

      【讨论】:

        猜你喜欢
        • 2018-11-30
        • 2012-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-13
        • 2014-12-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多