简体   繁体   English

C#结构初始化带有编译错误,但可以正常运行

[英]C# struct initialization with compile error but runs correctly

Inside XNA struct Vector2 are two public variables X and Y. I have the following code: 在XNA结构Vector2中,有两个公共变量X和Y。我有以下代码:

Vector2 v; Vector2 v; if(b) vX=1; if(b)vX = 1; else vY=2; 否则vY = 2;

//use v //使用v

The compiler gives "Use of unassigned local variable 'v'" But it runs correctly nonetheless. 编译器给出了“使用未分配的局部变量'v'”的提示,但是仍然可以正确运行。

Is there a more correct way of doing it? 有更正确的方法吗?

C#要求您在使用局部变量之前为它们分配一个值。

Vector2 v = new Vector2();

It works because a struct is automatically initialized. 之所以有效,是因为结构是自动初始化的。 All of its members are set to their Type's default value. 其所有成员均设置为其Type的默认值。 But if you use an unassigned variable like this, it's usually because you forgot to assign it before. 但是,如果您使用这样的未分配变量,通常是因为您之前忘记分配它。 I guess the compiler doesn't make a difference between structs and classes here. 我猜编译器在这里在结构和类之间没有区别。

Imho, this is a very bad idea. 恕我直言,这是一个非常糟糕的主意。 Structs in C# are value-types. C#中的结构是值类型。 C# imposes a number of restrictions to ensure that all fields of a struct are initialized: C#施加了许多限制以确保结构的所有字段都已初始化:

  • Default constructors are not allowed. 不允许使用默认构造函数。
  • Constructors must initialize all fields within the struct. 构造函数必须初始化结构中的所有字段。

If you do not instantiate a struct through a constructor, then all members are set to the result of calling default() on the member type. 如果不通过构造函数实例化结构,则所有成员都将设置为在成员类型上调用default()的结果。 This allows structs to be used in arrays. 这允许在数组中使用结构。 It also allows what you are doing, but is also the reason for the warning. 它还允许您在做什么,但这也是发出警告的原因。

Ideally, you should define a constructor and initialize the struct with the constructor. 理想情况下,您应该定义一个构造函数并使用该构造函数初始化该结构。

Edit: To clarify the restriction on the default (parameterless) constructor, you cannot explicitly define one, because the compiler provides one, which it uses to initializes all members. 编辑:要阐明对默认(无参数)构造函数的限制,您不能显式定义一个构造函数,因为编译器提供了一个构造函数,它用于初始化所有成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM