测试一个属性没有返回前空 [英] Test if a Property is not Null before Returning
问题描述
我有以下属性。
public MyType MyProperty {get;set;}
我要改变这个属性,这样,如果该值为null,它会首先填充值,然后返回...但的没有的使用私有成员变量
I want to change this property so that if the value is null, it'll populate the value first, and then return it... but without using a private member variable.
举例来说,如果我是这样做的:
For instance, if I was doing this:
public MyType MyProperty
{
get
{
if (_myProperty != null)
return _myProperty
else
_myProperty = XYZ;
return _myProperty;
}
set
{
_myProperty = value;
}
}
这可能吗?或者我需要的成员变量来完成它?
is this possible? Or do I need the member variable to get it done?
推荐答案
您需要一个成员变量和一个完整的财产申报。自动实现属性的只有的适用,如果他们围绕一个领域琐碎的包装,没有涉及到逻辑。你可以稍微简化的getter代码,顺便说一句:
You need a member variable and a full property declaration. Automatically implemented properties are only applicable if they're trivial wrappers around a field, with no logic involved. You can simplify your getter code slightly, btw:
get
{
if (_myProperty == null)
{
_myProperty = XYZ;
}
return _myProperty;
}
(注意,这一切都不是线程安全的,无需额外的锁定,但我。假设没关系)
(Note that none of this is thread-safe without extra locking, but I assume that's okay.)
顺便说一句,你已经有无的私有成员变量,如果您使用自动实现的属性 - 它只是编译器生成它。
By the way, you already have a private member variable if you're using automatically implemented properties - it's just that the compiler's generating it for you.
这篇关于测试一个属性没有返回前空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!