【发布时间】:2016-08-29 09:43:29
【问题描述】:
我想验证一个 null 属性,如果它是 NULL,我想返回一个空字符串。为此,我创建了一个如下所示的类:
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:
【问题讨论】:
-
如果你在做任何自定义代码,你就不能使用自动属性。对于自定义功能(就像您正在做的那样),您必须自己实现属性的代码(包括存储和从成员变量中检索值)。
标签: c# get set stack-overflow