C# 在重试之前验证null属性
我想验证一个null属性,如果它为null,我想返回一个空字符串。为此,我创建了一个类,如下所示:C# 在重试之前验证null属性,c#,get,set,stack-overflow,C#,Get,Set,Stack Overflow,我想验证一个null属性,如果它为null,我想返回一个空字符串。为此,我创建了一个类,如下所示: public class TestValue { public string CcAlias { get { return string.IsNullOrEmpty(CcAlias) ? string.Empty : CcAlias; } set { Cc
public class TestValue
{
public string CcAlias
{
get
{
return string.IsNullOrEmpty(CcAlias) ? string.Empty : CcAlias;
}
set
{
CcAlias = CcAlias ?? string.Empty;
}
}
}
并用以下代码测试了我的类:
private void TestMethod()
{
var testValue = new TestValue();
testValue.CcAlias = null;
MessageBox.Show(testValue.CcAlias);
//I thought an empty string will be shown in the message box.
}
不幸的是,错误即将发生,如下所述:
System.StackOverflowException was unhandled
HResult=-2147023895
Message=Exception of type 'System.StackOverflowException' was thrown.
InnerException:
您的setter和getter正在递归地调用自己:
set
{
CcAlias = CcAlias ?? string.Empty;
}
这将调用CcAlias
getter,该getter又一次调用自身(通过测试string.IsNullOrEmpty(CcAlias)
),导致堆栈溢出异常
您需要声明一个支持字段,并在setter中进行设置:
public class TestValue
{
private string __ccAlias = string.Empty; // backing field
public string CcAlias
{
get
{
// return value of backing field
return string.IsNullOrEmpty(_ccAlias) ? string.Empty : _ccAlias;
}
set
{
// set backing field to value or string.Empty if value is null
_ccAlias = value ?? string.Empty;
}
}
}
因此,您将字符串存储在支持字段\u ccAlias
中,getter返回该字段的值。
您的setter现在设置此字段。setter的参数在关键字值中传递
如果您正在执行任何自定义代码,则不能使用自动属性。对于自定义功能(就像您正在做的那样),您必须自己实现属性的代码(包括存储和检索成员变量的值)!非常感谢你让我了解这个问题。