简体   繁体   English

C#非整数枚举和转换

[英]C# Non-Integer enums and Casting

C# allows you to assign values to your enum elements such as C#允许您为枚举元素赋值,例如

public enum Animals
{
    Dog = 0, Cat = 1,
}

And You can cast too and from them like so. 而你也可以像他们一样投射他们。

public void demo()
{
    int dog = (int)Animals.Dog;
    Animals cat = (Animals)(dog++);
}

But c# also lets you do things like this 但是c#也可以让你做这样的事情

public enum Animals
{
    Dog = Vector2.One, Cat = Vector2.Zero,
}

However you cannot get the Vector2 back in and out with a cast. 但是你无法通过强制转换使Vector2重新进出。 such as

Vector2 dog = (Vector2)Animals.Dog; //this fails

Is this problem solvable? 这个问题可以解决吗? *Note Vector2 is a class object and Vector2.One and Vector2.Zero are static declarations of such. *注意Vector2是一个类对象, Vector2.OneVector2.Zero是这样的静态声明。 Which means Dog is assigned to a memory reference. 这意味着将Dog分配给内存引用。

The only way that C# will let you do C#允许你做的唯一方法

public enum Animals
{
    Dog = Vector2.One,
    Cat = Vector2.Zero
}

Is if there is an implicit cast from Vector2 to an integral type. 是否存在从Vector2到整数类型的隐式转换。 Otherwise, you will get a compile error. 否则,您将收到编译错误。 This is why you cannot cast back to Vector2 - there is no cast from int back to Vector2 . 这就是你无法转换回Vector2 - 没有从intVector2 Dog and Cat are integer valued, and the values come from the implicit cast from Vector2.One and Vector2.Zero to int , respectively. DogCat是整数值,值分别来自Vector2.OneVector2.Zeroint的隐式Vector2.One

You could define your own explicit cast to make it work, but I'm guessing you won't be able to get back all the information you want that way. 您可以定义自己的显式转换以使其正常工作,但我猜您将无法以这种方式获取所需的所有信息。

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

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