设置属性时,属性始终具有值吗? [英] Do properties always have a value when unset?

查看:114
本文介绍了设置属性时,属性始终具有值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的属性:

public Tuple<String, String>[] Breadcrumbs { get; set; }

我用一种这样的方法进行了测试:

and I have a test in one of my methods like this:

if (Breadcrumbs != null && Breadcrumbs.Length > 0) { }

根据调用此方法的时间,可能未设置面包屑。在一个测试中, Breadcrumbs == null 评估为true。

Depending on when this method is called, Breadcrumbs may not have been set. In one test, Breadcrumbs == null evaulates to true.

未设置的属性将始终具有值吗? (它将始终为 null ?)

Will unset properties always have a value? (Will it always be null?)

推荐答案

自动实现的未由任何代码明确设置的property始终具有该属性类型的默认值-对于引用类型为null。 (对于 int 它将为0,对于 char 则为'\0',等等。)

An automatically-implemented property which hasn't been explicitly set by any code will always have the default value for the property type - which is null for reference types. (For int it would be 0, for char it would be '\0' etc).

像这样的自动实现的属性 just 等效于:

An automatically implemented property like this is just equivalent to:

private PropertyType property;
public PropertyType Property
{
    get { return property; }
    set { property = value; }
}

...,只是后备变量的名称难以置信(您可以't在代码中引用它),因此它将始终以该类型的默认值开始。

... except that the backing variable has an unspeakable name (you can't refer to it in code) so it will always start off with the default value for the type.

这篇关于设置属性时,属性始终具有值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆