加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 未初始化的struct成员是否保证有值?

发布时间:2020-12-15 17:47:03 所属栏目:百科 来源:网络整理
导读:如果使用初始化列表创建结构,那么您省略的成员是否会获得已知的默认值? public struct Testing{ public int i; public double d; public string s;}Testing test = new Testing { s="hello" }; 我发现微软的一个链接暗示了它,但没有明确说明:Default Value
如果使用初始化列表创建结构,那么您省略的成员是否会获得已知的默认值?
public struct Testing
{
    public int i;
    public double d;
    public string s;
}

Testing test = new Testing { s="hello" };

我发现微软的一个链接暗示了它,但没有明确说明:Default Values Table (C# Reference).

一个小的测试程序显示它不会生成编译器错误并产生预期的结果.我知道最好不要依靠简单的测试来保证. http://ideone.com/nqFBIZ

解决方法

是的,它们包含默认值(T),其中T是值的类型.
对象引用将为null.

摘抄:

As described in Section 5.2,several kinds of variables are
automatically initialized to their default value when they are
created. For variables of class types and other reference types,this
default value is null. However,since structs are value types that
cannot be null,the default value of a struct is the value produced by
setting all value type fields to their default value and all reference
type fields to null.

取自这里:

http://msdn.microsoft.com/en-us/library/aa664475(v=vs.71).aspx

我记得在研究MOC时,他们明确说明了这一点.这是该语言的保证功能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读