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


当前回答

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

其他回答

面向对象的编程原则表明,类的内部工作应该对外界隐藏。如果公开一个字段,本质上就是公开类的内部实现。因此,我们用财产(Properties)(或Java中的方法)包装字段,使我们能够在不破坏代码的情况下更改实现。考虑到我们可以在Property中放置逻辑,还允许我们在需要时执行验证逻辑等。C#有一个可能令人困惑的自动属性概念。这允许我们简单地定义Property,而C#编译器将为我们生成私有字段。

public class Person
{
   private string _name;

   public string Name
   {
      get
      {
         return _name;
      }
      set
      {
         _name = value;
      }
   }
   public int Age{get;set;} //AutoProperty generates private field for us
}

财产用于显示字段。它们使用访问器(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; }
}

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

我对一个字段的设计是,一个字段只需要由它的父级修改,也就是类修改。结果变量变为私有,然后为了能够赋予读取外部类/方法的权限,我只使用Get来遍历属性系统。然后,该字段由属性检索,并且是只读的!如果你想修改它,你必须通过方法(例如构造函数),我发现由于这种方法使你安全,我们可以更好地控制代码,因为我们“法兰”。我们可以很好地将所有的事情都公开,所以每个可能的情况,变量/方法/类等的概念。。。在我看来,这只是对代码开发和维护的一种帮助。例如,如果一个人使用公共字段恢复代码,那么他可以做任何事情,因此可以做与目标相关的“不合逻辑”的事情,即代码编写的逻辑。这是我的观点。

当我使用经典模型私有字段/公共只读财产时,对于10个私有字段,我应该编写10个公共财产!代码可以更快地变大。我发现了私有setter,现在我只对私有setter使用公共财产。setter在后台创建一个私有字段。

这就是为什么我以前的经典编程风格是:

public class MyClass
{
 private int _id;
 public int ID { get { return _id; } }
 public MyClass(int id)
 {
  _id = id;
 }
}

我的新编程风格:

public class MyClass
{
 public int ID { get; private set; }
 public MyClass(int id)
 {
  ID = id;
 }
}

由于他们中的许多人已经解释了财产和Field的技术优缺点,现在是时候进入实时示例了。

1.财产允许您设置只读访问级别

考虑dataTable.Rows.Count和dataTable.Column[i].Caption的情况。它们来自dataTable类,对我们来说都是公共的。对它们的访问级别的不同之处在于,我们不能将值设置为dataTable.Rrows.Count,但我们可以读写dataTable.Colomn[i].Taption。这可以通过Field实现吗?不这只能通过财产完成。

public class DataTable
{
    public class Rows
    {       
       private string _count;        

       // This Count will be accessable to us but have used only "get" ie, readonly
       public int Count
       {
           get
           {
              return _count;
           }       
       }
    } 

    public class Columns
    {
        private string _caption;        

        // Used both "get" and "set" ie, readable and writable
        public string Caption
        {
           get
           {
              return _caption;
           }
           set
           {
              _caption = value;
           }
       }       
    } 
}

2.PropertyGrid中的财产

您可能在Visual Studio中使用了Button。它的财产显示在PropertyGrid中,如Text、Name等。当我们拖放按钮时,当我们单击财产时,它将自动找到类button并过滤财产,并在Property Grid中显示该类(其中PropertyGrid不会显示Field,即使它们是公共的)。

public class Button
{
    private string _text;        
    private string _name;
    private string _someProperty;

    public string Text
    {
        get
        {
           return _text;
        }
        set
        {
           _text = value;
        }
   } 

   public string Name
   {
        get
        {
           return _name;
        }
        set
        {
           _name = value;
        }
   } 

   [Browsable(false)]
   public string SomeProperty
   {
        get
        {
           return _someProperty;
        }
        set
        {
           _someProperty= value;
        }
   } 

在PropertyGrid中,将显示财产Name和Text,但不显示SomeProperty。为什么?因为财产可以接受属性。如果[可浏览(false)]为false,则不会显示。

3.可以在财产中执行语句

public class Rows
{       
    private string _count;        


    public int Count
    {
        get
        {
           return CalculateNoOfRows();
        }  
    } 

    public int CalculateNoOfRows()
    {
         // Calculation here and finally set the value to _count
         return _count;
    }
}

4.绑定源中只能使用财产

绑定源帮助我们减少代码行数。BindingSource不接受字段。为此,我们应该使用财产。

5.调试模式

考虑我们使用Field来保存值。在某些时候,我们需要调试并检查该字段的值在哪里变为空。当代码行数超过1000行时,这将很难做到。在这种情况下,我们可以使用Property,并可以在Property中设置调试模式。

   public string Name
   {
        // Can set debug mode inside get or set
        get
        {
           return _name;
        }
        set
        {
           _name = value;
        }
   }