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


当前回答

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

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

非常有用的功能。

其他回答

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

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

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

来自维基百科——面向对象编程:

面向对象编程(OOP)是一种基于“对象”概念的编程范式,“对象”是以字段形式包含数据的数据结构,通常称为属性;和代码,以过程的形式,通常称为方法。(添加强调)

财产实际上是对象行为的一部分,但其设计是为了给对象的消费者提供使用对象数据的幻觉/抽象。

在后台,属性被编译为方法。因此,Name属性被编译为get_Name()和set_Name(字符串值)。如果您研究编译的代码,您可以看到这一点。因此,在使用它们时会有(非常)小的性能开销。通常,如果向外部公开字段,则始终使用Property,如果需要验证值,则通常在内部使用Property。

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

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

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

例如:

您可以在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

}