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


当前回答

字段是类中的变量。字段是可以通过使用访问修饰符封装的数据。

财产与字段类似,它们定义与对象关联的状态和数据。

与字段不同,属性有一种特殊的语法来控制用户如何读取数据和写入数据,这些被称为get和set运算符。集合逻辑通常可用于进行验证。

其他回答

想想看:你有一个房间和一扇门可以进入这个房间。如果你想检查谁是如何进来并保护你的房间的,那么你应该使用财产,否则他们不会是任何门,每个人都很容易进来,没有任何规定

class Room {
   public string sectionOne;
   public string sectionTwo;
}

Room r = new Room();
r.sectionOne = "enter";

人们很容易进入第一区,没有任何检查

class Room 
{
   private string sectionOne;
   private string sectionTwo;

   public string SectionOne 
   {
      get 
      {
        return sectionOne; 
      }
      set 
      { 
        sectionOne = Check(value); 
      }
   }
}

Room r = new Room();
r.SectionOne = "enter";

现在你检查了这个人,知道他是否有什么不好的地方

如果要使用线程原语,则必须使用字段。财产可以破坏线程代码。除此之外,科里所说的是正确的。

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

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

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

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

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

从技术上讲,我不认为有什么区别,因为财产只是围绕用户创建的或编译器自动创建的字段的包装器。财产的目的是加强封装,并提供轻量级的类方法功能。将字段声明为公共字段是一种不好的做法,但它没有任何问题。

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