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


当前回答

传统上,私有字段是通过getter和setter方法设置的。为了减少代码,您可以使用财产来设置字段。

其他回答

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

例子:

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

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

财产是一种特殊的类成员。在财产中,我们使用预定义的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;
    }
}

财产的主要优点是允许您更改对象上数据的访问方式,而不会破坏其公共接口。例如,如果您需要添加额外的验证,或者将存储的字段更改为计算字段,那么如果您最初将字段作为属性公开,则可以很容易地执行此操作。如果您只是直接公开了一个字段,那么您必须更改类的公共接口以添加新功能。这种改变会破坏现有的客户机,要求他们在使用新版本的代码之前重新编译。

如果您编写了一个为广泛使用而设计的类库(如数百万人使用的.NET Framework),这可能是一个问题。然而,如果您正在编写一个在小代码库内部使用的类(例如<=50K行),这真的不是什么大问题,因为没有人会受到您的更改的负面影响。在这种情况下,这真的只是个人喜好。

此外,财产允许您在设置值时使用逻辑。

因此,如果值大于x,您可以说只想将值设置为整数字段,否则将引发异常。

非常有用的功能。

IMO,财产只是我们以前使用的“SetXXX()”“GetXX()”函数/方法/接口对,但它们更简洁优雅。