在C#中,是什么使字段与属性不同?何时应该使用字段而不是属性?


当前回答

财产支持非对称访问,即您可以有getter和setter,也可以只有这两者之一。类似地,财产支持getter/setter的单独可访问性。字段始终是对称的,即您始终可以获取和设置值。例外情况是只读字段,在初始化后显然无法设置。

财产可能运行很长时间,有副作用,甚至可能引发异常。字段很快,没有副作用,并且不会抛出异常。由于副作用,属性可能会为每个调用返回不同的值(DateTime.Now可能就是这样,即DateTime.Nnow不总是等于DateTime.NNow)。字段总是返回相同的值。

字段可以用于out/ref参数,财产则不能。财产支持额外的逻辑–这可以用于实现延迟加载等。

财产通过封装获取/设置值的任何含义来支持抽象级别。

在大多数/所有情况下使用财产,但尽量避免副作用。

其他回答

基本区别和一般区别是:

领域

始终给予get和set访问权限不会造成副作用(引发异常、调用方法、更改字段(获取/设置的字段除外)等)

财产

并非总是同时提供get和set访问权限CAN导致副作用

财产显示字段。字段应该(几乎总是)对类保持私有,并通过get和set财产进行访问。财产提供了一个抽象级别,允许您更改字段,同时不影响使用类的事物访问字段的外部方式。

public class MyClass
{
    // this is a field.  It is private to your class and stores the actual data.
    private string _myField;

    // this is a property. When accessed it uses the underlying field,
    // but only exposes the contract, which will not be affected by the underlying field
    public string MyProperty
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }

    // This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
    // used to generate a private field for you
    public int AnotherProperty { get; set; } 
}

@Kent指出,财产不需要封装字段,它们可以对其他字段进行计算,也可以用于其他目的。

@GSS指出,您还可以在访问属性时执行其他逻辑,例如验证,这是另一个有用的功能。

我将举几个使用财产的示例,这些属性可能会使齿轮转动:

惰性初始化:如果您有一个对象的属性,该属性的加载成本很高,但在正常运行代码时无法访问,则可以通过该属性延迟加载。这样,它就只是坐在那里,但当另一个模块第一次尝试调用该属性时,它会检查基础字段是否为空-如果为空,它会继续加载它,调用模块不知道。这可以大大加快对象初始化。肮脏追踪:这是我从StackOverflow上的问题中了解到的。当我有很多对象的值可能在运行期间发生了变化时,我可以使用该属性来跟踪它们是否需要保存回数据库。如果对象的任何一个属性都没有改变,IsDirty标志都不会被触发,因此保存功能在决定需要返回数据库时会跳过它。

财产是一种特殊的类成员。在财产中,我们使用预定义的Set或Get方法。它们使用访问器,通过访问器我们可以读取、写入或更改私有字段的值。

例如,让我们使用一个名为Employee的类,其中包含name、age和Employee_Id的私有字段。我们无法从类外部访问这些字段,但可以通过财产访问这些私有字段。

我们为什么使用财产?

公开类字段并公开它是有风险的,因为您无法控制分配和返回的内容。

为了通过示例清楚地理解这一点,让我们以一个具有ID、密码和姓名的学生班级为例。现在在这个例子中,公共领域的一些问题

ID不应为-ve。名称不能设置为空合格标记应为只读。如果缺少学生姓名,则不应返回姓名。

为了解决这个问题,我们使用Get和set方法。

// A simple example
public class student
{
    public int ID;
    public int passmark;
    public string name;
}

public class Program
{
    public static void Main(string[] args)
    {
       student s1 = new student();
       s1.ID = -101; // here ID can't be -ve
       s1.Name = null ; // here Name can't be null
    }
}

现在我们以get和set方法为例

public class student
{
    private int _ID;
    private int _passmark;
    private string_name ;
    // for id property
    public void SetID(int ID)
    {
        if(ID<=0)
        {
            throw new exception("student ID should be greater then 0");
        }
        this._ID = ID;
    }
    public int getID()
    {
        return_ID;
    }
}
public class programme
{
    public static void main()
    {
        student s1 = new student ();
        s1.SetID(101);
    }
    // Like this we also can use for Name property
    public void SetName(string Name)
    {
        if(string.IsNullOrEmpty(Name))
        {
            throw new exeception("name can not be null");
        }
        this._Name = Name;
    }
    public string GetName()
    {
        if( string.IsNullOrEmpty(This.Name))
        {
            return "No Name";
        }
        else
        {
            return this._name;
        }
    }
        // Like this we also can use for Passmark property
    public int Getpassmark()
    {
        return this._passmark;
    }
}

其他信息:默认情况下,get和set访问器与属性本身一样可访问。通过对访问器应用更严格的访问修饰符,可以分别控制/限制访问器的可访问性(对于get和set)。

例子:

public string Name
{
    get
    {
        return name;
    }
    protected set
    {
        name = value;
    }
}

这里get仍然是公共访问的(因为属性是公共的),但set是受保护的(一个更受限制的访问说明符)。