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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/csharp/96939.html

猜你在找的C#相关文章