为什么我的 属性 的支持字段没有改变它的值?
Why does the backing field of my property not change its value?
namespace tutor4
{
class Class1
{
int _num = 2;
public int num
{
get
{
return _num;
}
set
{
_num = num;
}
}
public void incrementFunction()
{
num++;
Console.WriteLine("The value of _num is "+ num);
}
}
}
namespace tutor4
{
class Program
{
static void Main(string[] args)
{
Class1 class1Obj = new Class1();
for(int i=0;i<7;i++)
class1Obj.incrementFunction();
}
}
不知道为什么_num
不增加,谁能解释一下?
你的 setter num
属性 是错误的。
应该不是
set
{
_num = num;
}
因为在这种情况下它什么都不做(将 _num 设置回它的值,因为 getter for num
returns _num
所以这一行等同于 _num = _num
)
应该是
set
{
_num = value;
}
关于 value 关键字的 MSDN 解释:
The contextual keyword value is used in the set accessor in ordinary
property declarations. It is similar to an input parameter on a
method. The word value references the value that client code is
attempting to assign to the property
另请注意:您的 num
属性 只是 class 的 _num
字段的简单包装。如果您不需要 getter 和 setter 中的一些复杂逻辑来实现此 属性 - 您可以将其更改为 auto-implemented 属性,如下所示:
class Class1
{
public int num { get; set;}
public Class1
{
num = 2;
}
}
在 C# 版本 6 之前,您应该将默认值分配给 class 构造函数中自动实现的 属性。
在 C# 版本 6(尚未发布,应该在今年夏天可用)中,您将能够在声明中为自动实现的 属性 分配默认值:
public int num { get; set;} = 2;
namespace tutor4
{
class Class1
{
int _num = 2;
public int num
{
get
{
return _num;
}
set
{
_num = num;
}
}
public void incrementFunction()
{
num++;
Console.WriteLine("The value of _num is "+ num);
}
}
}
namespace tutor4
{
class Program
{
static void Main(string[] args)
{
Class1 class1Obj = new Class1();
for(int i=0;i<7;i++)
class1Obj.incrementFunction();
}
}
不知道为什么_num
不增加,谁能解释一下?
你的 setter num
属性 是错误的。
应该不是
set
{
_num = num;
}
因为在这种情况下它什么都不做(将 _num 设置回它的值,因为 getter for num
returns _num
所以这一行等同于 _num = _num
)
应该是
set
{
_num = value;
}
关于 value 关键字的 MSDN 解释:
The contextual keyword value is used in the set accessor in ordinary property declarations. It is similar to an input parameter on a method. The word value references the value that client code is attempting to assign to the property
另请注意:您的 num
属性 只是 class 的 _num
字段的简单包装。如果您不需要 getter 和 setter 中的一些复杂逻辑来实现此 属性 - 您可以将其更改为 auto-implemented 属性,如下所示:
class Class1
{
public int num { get; set;}
public Class1
{
num = 2;
}
}
在 C# 版本 6 之前,您应该将默认值分配给 class 构造函数中自动实现的 属性。
在 C# 版本 6(尚未发布,应该在今年夏天可用)中,您将能够在声明中为自动实现的 属性 分配默认值:
public int num { get; set;} = 2;