C# 设置可为空属性默认值的首选方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/17064604/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Preferred way to set default values of nullable properties?
提问by Konrad Viltersten
I'm in a dilemma. The (reduced) task is to redesign the following data holder class
我进退两难。(减少的)任务是重新设计以下数据持有者类
class Stuff
{
  public String SomeInfo { get; set; }
}
to accommodate the demand that nullmustn't be returned. I can think of two ways to achieve that and after deep consideration of 15 minutes, I simply can't decide which one is to be preferred.
以满足不能返回null的需求。我可以想到两种方法来实现这一目标,经过 15 分钟的深思熟虑后,我根本无法决定更喜欢哪一种。
Approach by constructor.
构造函数的方法。
class Stuff
{
  public String SomeInfo { get; set; }
  public Stuff() { SomeInfo = String.Empty; }
}
Approach by property.
按属性方法。
class Stuff
{
  private String _SomeInfo;
  public String SomeInfo 
  { 
    get { return _SomeInfo ?? String.Empty; }
    set { _SomeInfo = value; }
  }
}
Note that the creation of the Stuffinstances might be done using the constructor as well as initialization, if that's of any significance. As far as I'm informed, there won't be any other restrictions (but you know how the customers' specifications not always reflect the reality).
请注意,如果有任何意义,可以使用构造函数和初始化来创建Stuff实例。据我所知,不会有任何其他限制(但您知道客户的规格并不总是反映现实)。
采纳答案by Tim Schmelter
You can only ensure that nullis never returned when you use the property:
您只能确保null在使用该属性时永远不会返回:
class Stuff
{
  private String _SomeInfo;
  public String SomeInfo 
  { 
    get { return _SomeInfo ?? String.Empty; }
    set { _SomeInfo = value; }
  }
}
The same approach is used by text-controls(e.g. in ASP.NET) where the Textproperty never returns nullbut String.Empty. 
文本控件(例如在 ASP.NET 中)使用相同的方法,其中Text属性从不返回null但String.Empty.
For example(ILSpy):
例如(ILSpy):
// System.Web.UI.WebControls.TextBox
public virtual string Text
{
    get
    {
        string text = (string)this.ViewState["Text"];
        if (text != null)
        {
            return text;
        }
        return string.Empty;
    }
    set
    {
        this.ViewState["Text"] = value;
    }
}
回答by vc 74
You can also implement the logic in the setter rather than in the getter, that way your back field always has a valid value
您还可以在 setter 中而不是在 getter 中实现逻辑,这样您的 back 字段始终具有有效值
class Stuff
{
  private String _SomeInfo = string.Empty;
  public String SomeInfo 
  { 
    get { return _SomeInfo; }
    set 
    { 
      if (value != null)
      {
        _SomeInfo = value; 
      }
    }
  }
}
回答by uk2k05
Just to add another answer to this, you can also set a default value to a string object in a single statement;
只是为此添加另一个答案,您还可以在单个语句中为字符串对象设置默认值;
class Stuff
{
  private String Something {get; set;} = string.Empty;
}

