Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在重试之前验证null属性_C#_Get_Set_Stack Overflow - Fatal编程技术网

C# 在重试之前验证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

我想验证一个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: 

您的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的参数在关键字
值中传递

如果您正在执行任何自定义代码,则不能使用自动属性。对于自定义功能(就像您正在做的那样),您必须自己实现属性的代码(包括存储和检索成员变量的值)!非常感谢你让我了解这个问题。