返回前验证 null 属性
Validate null property before returing
我想验证一个 null 属性,如果它是 NULL,我想 return 一个空字符串。为此,我创建了一个如下所示的 class:
public class TestValue
{
public string CcAlias
{
get
{
return string.IsNullOrEmpty(CcAlias) ? string.Empty : CcAlias;
}
set
{
CcAlias = CcAlias ?? string.Empty;
}
}
}
并使用以下代码测试了我的 class:
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.WhosebugException was unhandled
HResult=-2147023895
Message=Exception of type 'System.WhosebugException' was thrown.
InnerException:
您的 setter 和 getter 正在递归调用自己:
set
{
CcAlias = CcAlias ?? string.Empty;
}
这会调用 CcAlias
getter,后者又会再次调用 自身 (通过测试 string.IsNullOrEmpty(CcAlias)
),一次又一次,导致WhosebugException
.
您需要声明一个支持字段并在您的 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;
}
}
}
因此,您将字符串存储在支持字段 _ccAlias
中,而 getter returns 该字段的值。
您的 setter 现在设置了这个字段。 setter 的参数在关键字 value
.
中传递
我想验证一个 null 属性,如果它是 NULL,我想 return 一个空字符串。为此,我创建了一个如下所示的 class:
public class TestValue
{
public string CcAlias
{
get
{
return string.IsNullOrEmpty(CcAlias) ? string.Empty : CcAlias;
}
set
{
CcAlias = CcAlias ?? string.Empty;
}
}
}
并使用以下代码测试了我的 class:
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.WhosebugException was unhandled
HResult=-2147023895
Message=Exception of type 'System.WhosebugException' was thrown.
InnerException:
您的 setter 和 getter 正在递归调用自己:
set
{
CcAlias = CcAlias ?? string.Empty;
}
这会调用 CcAlias
getter,后者又会再次调用 自身 (通过测试 string.IsNullOrEmpty(CcAlias)
),一次又一次,导致WhosebugException
.
您需要声明一个支持字段并在您的 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;
}
}
}
因此,您将字符串存储在支持字段 _ccAlias
中,而 getter returns 该字段的值。
您的 setter 现在设置了这个字段。 setter 的参数在关键字 value
.