3

好吧,我正在学习属性,但我不确定以下内容:

class X
{
  private int y;

  public X(int number)
  {
    this.Y=number; // assign to property
    OR
   this.y=number //?
  }

  public int Y;
  {
    get; set;  
  }

}
4

7 回答 7

1

当您使用自动属性(get; set;或其变体)时,无法访问支持变量。在大多数情况下,这些可以被视为简单的变量,尤其是在内部。

如果您需要在 mutator 中执行自定义验证或突变逻辑,或者需要显式支持变量,则不能使用自动属性,而必须自己编写存根getset方法。

于 2011-02-25T10:37:06.887 回答
1

他们做不同的事情;我会做Y = number;删除(未使用的)字段y。在一个自动实现的属性中,编译器会创建它自己的字段(具有在 C# 中看不到的可怕名称)——您不需要提供自己的字段。所以:

class X
{
  public X(int y)
  {
    Y = y;
  }
  public int Y { get; set; }    
}

其他要点:更改numbery对调用者更清楚,而且您也不需要this.,因为它不是模棱两可的(字段与参数等)。

于 2011-02-25T10:37:13.240 回答
1

仅分配给表示该字段的属性内的字段(私有 int y)(公共 int Y {get;set})。 类中的其他任何地方都不应直接分配支持字段。总是通过属性来做......是的,即使在构造函数中也是如此。它遵循不重复自己 ( DRY ) 原则。

建议这样做,因为将来无论何时您想要关联由该分配触发的某些行为,您只有一个位置(set 访问器)可以将代码写入......而不是该字段分配到的所有位置!

   class X   
   {   
    private int y; //not strictly necessary but good for documentation

    public X(int number)
    {
        Y = number;
    }

    public int Y { get; set; }


    }
于 2011-02-25T10:49:30.193 回答
0

当您使用自动属性时:

  public int Y;
  {
    get; set;  
  }

你不需要私有属性,因为它是自动生成的。所以你的班级将是:

class X
{   
  public X(int number)
  {
    Y = number;
  }

  public int Y // no semicolon here, comment added for edit length
  {
    get; set;  
  }
}

希望这可以帮助

于 2011-02-25T10:36:39.623 回答
0

你有两个选择:

class X
{
    private int y;

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public X(int number)
    {
        Y = number;
        //equivalent to 
        y = number;
        // but you should use the public property setter instead of the private field
    }
}

或者使用 auto-properties ,它甚至更简单:

class X
{
    private int y;

    public int Y
    {
        get; set;
    }

    public X(int number)
    {
        Y = number;
    }
}
于 2011-02-25T10:43:18.357 回答
0

当不使用自动属性时,我总是使用属性设置器,因为设置器中可能或将会有我需要执行的代码。此代码可以是域检查或引发诸如 PropertyChanged 之类的事件。

于 2011-02-25T10:44:37.657 回答
0

关于访问支持变量,我通常会尝试提出一点:

有时,公共 getter 可能包含复杂的数据验证、引发属性更改事件或在某些外部代码更改其值时触发的其他一些复杂代码。

在内部(从类内部)更改该值时,如果您的意图是跳过来自公共设置器的所有验证和事件,则直接使用支持变量可能是一个有效点。这就像说“我是班级实例,我知道自己在做什么”。这样,公共设置器就像看门狗一样,清理外部输入,而我仍然可以在内部将属性设置为我需要的任何内容。

class X   
   {   
     private int y; //not strictly necessary but good for documentation

    public X(int number)
    {
        y = GetYValueFromDB();  //we assume the value from DB is already valid

    }

    public int Y { 
       get{ return y}; 
       set { 
       if (ComplexValidation(value)
         {
           RaiseOnYPropertyChanged();
           y = value;
         }
        }


    }
于 2011-02-25T11:18:52.937 回答