取消设置时,属性是否始终具有值?

Oli*_*ver 7 .net c# properties

我有这样的房产:

public Tuple<String, String>[] Breadcrumbs { get; set; }
Run Code Online (Sandbox Code Playgroud)

我在我的一个方法中测试过这样的测试:

if (Breadcrumbs != null && Breadcrumbs.Length > 0) { }
Run Code Online (Sandbox Code Playgroud)

根据调用此方法的时间,Breadcrumbs可能尚未设置.在一次测试中,Breadcrumbs == null评估为真.

未设置的属性是否总有价值?(会不会是null?)

Jon*_*eet 19

未经任何代码显式设置的自动实现的属性将始终具有属性类型的默认值 - 对于引用类型,该值为null.(因为int它将是0,因为char它将是'\ 0'等).

像这样自动实现的属性相当于:

private PropertyType property;
public PropertyType Property
{
    get { return property; }
    set { property = value; }
}
Run Code Online (Sandbox Code Playgroud)

...除了支持变量具有不可描述的名称(您无法在代码中引用它),因此它始终以该类型的默认值开始.