【问题标题】:Is there value in creating a property for a readonly field [duplicate]为只读字段创建属性是否有价值[重复]
【发布时间】:2019-08-23 03:05:23
【问题描述】:

在创建不可变类型时,为只读字段创建属性是否有任何价值?

公共只读字段:

public class MyClass 
{
    public readonly string MyText;

    public MyClass (string theText)     
    {
        MyText = theText;
    }
}

具有公共属性的私有只读字段:

public class MyClass 
{
    private readonly string myText;

    public string MyText    
    {
        get { return myText; }
    }

    public MyClass(string theText)  
    {
        myText = theText;
    }
}

【问题讨论】:

  • here。我猜你想在第二个代码示例中返回 myText。

标签: c# properties field


【解决方案1】:

字段通常用于包含实现细节。出于这个原因,他们should not be declared in a manner that is visible 到其他代码库。公共的非内部字段将违反此规则。如果调用者直接使用这些字段,它们就违反了实现应该依赖于抽象的一般 SOLID 原则。

此外,属性相对于字段具有一定的优势。属性可以包含在接口中,例如fields cannot。此外,属性可以是虚拟的、抽象的和被覆盖的,而 fields cannot

【讨论】:

    【解决方案2】:

    作为@John Wu 回答的补充:

    在 C# 6 及更高版本中,您可以使用只能在构造函数中分配的只读属性:

    public string MyText { get; }
    

    这使您不必拥有仅用于支持此属性的支持字段。

    但故事并没有到此结束,属性不是字段而是方法

    知道了这一点,它可以让你实现一个领域无法做到的事情,例如:

    通过实现INotifyPropertyChanged 通知值更改:

    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    
    public class Test : INotifyPropertyChanged
    {
        private string _text;
    
        public string Text
        {
            get => _text;
            set
            {
                if (value == _text)
                    return;
    
                _text = value;
                OnPropertyChanged();
            }
        }
    
        #region INotifyPropertyChanged Members
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        #endregion
    
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    作为一个可以绑定的值:

    在 WPF 和 UWP 中,您只能绑定到属性,而不是字段。

    最后:

    这取决于您的要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      相关资源
      最近更新 更多