简体   繁体   中英

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:

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

//use v

The compiler gives "Use of unassigned local variable 'v'" But it runs correctly nonetheless.

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. 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# imposes a number of restrictions to ensure that all fields of a struct are initialized:

  • 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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