微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如果使用初始化列表创建结构,那么您省略的成员是否会获得已知的认值?
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时,他们明确说明了这一点.这是该语言的保证功能.

原文地址:https://www.jb51.cc/csharp/96939.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐