简体   繁体   English

不可为空的字符串初始化为Null

[英]Non-Nullable String Initializes as Null

I trying to understand why a non-nullable string initializes to null instead of an empty string. 我试图理解为什么非空字符串初始化为null而不是空字符串。 For example: 例如:

//Property of class foo
public string Address_Notes { get; set; }

//Create instance of foo
foo myFoo = new foo();

//Get value of Address_Notes
var notesValue = myFoo.Address_Notes; //Returns null

Am I crazy to think that a non-nullable string's value should default to String.Empty ? 我以为不可为空的字符串的值应默认为String.Empty感到疯狂吗? Is there a standard way of forcing this behavior, other than a custom getter? 除了自定义getter之外,是否有强制这种行为的标准方法?

There is no such thing as a "non-nullable string". 没有“不可为空的字符串”之类的东西。

String is a reference type, so its default value is indeed a null. 字符串是引用类型,因此其默认值确实为null。

You could get around the issue by setting the value to String.Empty in the constructor for your class (foo). 您可以通过在类(foo)的构造函数中将值设置为String.Empty来解决此问题。

字符串是引用类型,始终为可为空。

String is reference type - values are initialized to null by default. 字符串是引用类型-默认情况下,值初始化为null

You can initialize strings in constructor to string.Empty , and it is best practice to do it, because: 您可以将构造函数中的字符串初始化为string.Empty ,并且这样做是最佳实践,因为:

  • null value means "I do not know what is the value" null值表示“我不知道值是多少”
  • string.Empty means "value is empty" or "value does not exists". string.Empty表示“值为空”或“值不存在”。

So, almost every string properties should be (by you) initialized to string.Empty value. 因此,几乎每个字符串属性都应(由您)初始化为string.Empty值。 Try to read something about "null object pattern". 尝试阅读有关“空对象模式”的内容。 Programming according this principle makes much more readable and bug-proof code. 根据此原理进行编程可以使代码更具可读性和防错性。

Since you are using properties to get the string values, another option is to return string.Empty if it is in fact null. 由于您使用属性来获取字符串值,因此另一个选择是返回string.Empty(如果实际上为null)。

//Property of class foo
private string _address_Notes;
public string Address_Notes 
{ 
    get { return _address_Notes ?? string.Empty; } 
    set { _address_Notes = value; }
}

A much better solution would be to initialise the string to string.Empty (if that is your expected behaviour). 更好的解决方案是将字符串初始化为string.Empty(如果这是您的预期行为)。 You can do this in C# 6+ as follows: 您可以在C#6+中执行以下操作:

public string Address_Notes { get; set; } = string.Empty;

This way it's a one off initialisation rather than a check on every request. 这样,它是一次性的初始化,而不是对每个请求的检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM