gpt4 book ai didi

c# - 为什么我的属性的支持字段没有改变它的值?

转载 作者:行者123 更新时间:2023-11-30 18:54:39 25 4
gpt4 key购买 nike

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不增加,谁能解释一下?

最佳答案

num 属性的 setter 是错误的。

它应该

set
{
_num = num;
}

因为在这种情况下它什么都不做(将 _num 设置回它的值,因为 num 的 getter 返回 _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 属性只是类的 _num 字段的简单包装。如果您不需要此属性的 getter 和 setter 中的一些复杂逻辑 - 您可以将其更改为 auto-implemented像这样的属性:

class Class1
{
public int num { get; set;}

public Class1
{
num = 2;
}
}

在 C# 版本 6 之前,您应该在类构造函数中为自动实现的属性分配默认值。

在 C# 版本 6(尚未发布,应该在今年夏天可用)中,您将能够在声明中为自动实现的属性分配默认值:

public int num { get; set;} = 2;

关于c# - 为什么我的属性的支持字段没有改变它的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31455367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com