注意:这不是关于自动实现属性的问题。自动实现的属性是关于在 getter 和 setter 中没有逻辑的属性,而我在我的代码中非常清楚地声明有一些逻辑。这不是 this question 的副本两者都不是,因为问题确实不同,答案也是如此。
我看到了很多这样的:
private int _age;
public int Age
{
get
{
if(user.IsAuthorized)
{
return _age;
}
}
set
{
if(value >= 0 && value <= 120)
{
_age = value;
}
else
{
throw new ArgumentOutOfRangeException("Age","We do not accept immortals, nor unborn humans...");
}
}
}
但为什么我们需要支持字段?为什么不归还属性(property)本身?
public object Age
{
get
{
if(user.IsAuthorized)
{
return Age;
}
}
set
{
if(value >= 0 && value <= 120)
{
Age = value;
}
else
{
throw new ArgumentOutOfRangeException("Age","We do not accept immortals, nor unborn humans...");
}
}
}
最佳答案
好吧,返回属性本身会导致堆栈溢出异常:
public object Property
{
get
{
return Property;
}
set
{
Property = value;
}
}
想象
MyObject o = new MyObject();
// cause Stack Overflow exception
o.Property = null;
原因很简单:
- 设置
Property = null
调用set
- 调用
Property = value;
进而调用set
- 调用
Property = value;
...等等。
因此,如果属性存储一些值,则该值应存储在字段(您需要一个字段)中,我们不能使用属性来存储本身。如果您想缩短代码,请这样写(自动属性):
public object Property {
get; // let .Net create a backing field for you
set;
}
关于c# - 为什么我们需要 C# 属性中的支持字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431888/