在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";

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

这里清楚地解释了区别。然而,只是为了总结和强调:

字段封装在类内部以进行内部操作,而财产可用于将类公开给外部世界,以及共享链接中显示的其他内部操作。此外,如果您希望基于特定字段的值加载某些方法或用户控件,则属性将为您完成此操作:

例如:

您可以在asp.net页面中的用户控件下方运行,只需为aspx页面中控件的Id前缀赋值,如下所示:

useMeId.Id=5 ---call the property of user control "UseMe.ascx"

使用Me.ascx

<%@ Register Src=~/"UseMe.ascx" TagPrefix="uc" TagName="UseMe" %>
<uc:UseMe runat="Server" id="useMeId" />

UseMe.ascx.cs

private int currentId;

public int Id
   {
      get
      {
         return currentId;
      }
      set
      {
         currentId = value;
       LoadInitialData(currentId);
      }
   }
Private void LoadinitialData(int currentIdParam)
{
//your action

}

财产显示字段。字段应该(几乎总是)对类保持私有,并通过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指出,您还可以在访问属性时执行其他逻辑,例如验证,这是另一个有用的功能。

财产用于显示字段。它们使用访问器(set、get),通过这些访问器可以读取、写入或操作私有字段的值。

财产不指定存储位置。相反,它们具有读取、写入或计算其值的访问器。

使用财产,我们可以对字段上设置的数据类型进行验证。

例如,我们有一个私有整数字段age,我们应该允许正值,因为age不能为负值。

我们可以使用getter和setter以及使用property两种方式来实现这一点。

 Using Getter and Setter

    // field
    private int _age;

    // setter
    public void set(int age){
      if (age <=0)
       throw new Exception();

      this._age = age;
    }

    // getter
    public int get (){
      return this._age;
    }

 Now using property we can do the same thing. In the value is a key word

    private int _age;

    public int Age{
    get{
        return this._age;
    }

    set{
       if (value <= 0)
         throw new Exception()
       }
    }

如果我们在get和set访问器中没有逻辑,我们可以使用自动实现的属性。

当使用自动实现的属性编译时,将创建一个只能通过get和set访问器访问的私有匿名字段。

public int Age{get;set;}

抽象财产抽象类可以具有抽象属性,该属性应在派生类中实现

public abstract class Person
   {
      public abstract string Name
      {
         get;
         set;
      }
      public abstract int Age
      {
         get;
         set;
      }
   }

// overriden something like this
// Declare a Name property of type string:
  public override string Name
  {
     get
     {
        return name;
     }
     set
     {
        name = value;
     }
  }

我们可以私下设置房产在这种情况下,我们可以私下设置auto属性(在类中设置)

public int MyProperty
{
    get; private set;
}

您可以使用此代码实现相同的效果。在该属性集中,由于我们必须直接将值设置为字段,因此功能不可用。

private int myProperty;
public int MyProperty
{
    get { return myProperty; }
}

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