非空的字符串初始化为Null [英] Non-Nullable String Initializes as Null
问题描述
我试图理解为什么一个非空的字符串初始化为空,而不是一个空字符串。例如:
I trying to understand why a non-nullable string initializes to null instead of an empty string. 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
我是疯了,认为一个非空的字符串的值应该默认为的String.Empty
?是否有强制这种行为,不是一个自定义的getter其他的标准方式?
Am I crazy to think that a non-nullable string's value should default to String.Empty
? Is there a standard way of forcing this behavior, other than a custom getter?
推荐答案
有作为非没有这样的事情-nullable字符串。
There is no such thing as a "non-nullable string".
字符串是引用类型,所以它的默认值是确实是一个空。
String is a reference type, so its default value is indeed a null.
您可以通过在构造函数中为类(富)的值设置为的String.Empty
解决这个问题。
You could get around the issue by setting the value to String.Empty
in the constructor for your class (foo).
这篇关于非空的字符串初始化为Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!