C# Structs: Unassigned local variable?

前端 未结 2 931
挽巷
挽巷 2020-11-29 08:21

From the documentation:

Unlike classes, structs can be instantiated without using a new operator.

So why am I getting this error

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 08:55

    It is still uninitialized. You need to initialize it before using it. You can use default operator for that if you don't want to create a static Vec.Empty value and happy with the defaults for the structs members:

    Vec2 x = default(Vec2);
    

    Mitch Wheat:

    This, however doesn't:

    public struct Vec2
    {
        int x;
        int y;
    
       public float X { get { return x; } set { x = value; } }
       public float Y { get { return y; } set { y = value; } }
    
    }
    static void Main(string[] args)
    {
        Vec2 x;
    
        x.X = 1;
        x.Y = 2; 
    }
    

    The compiler prevents you from calling propertis on types before all of it's members have been initialized, even though a property might just set one of the values. The solution, as Jon Skeet proposed, is to have an initializing constructor and preferably no setters.

提交回复
热议问题