简体   繁体   English

C#:do enums在上下文中将自己强制转换为字符串或整数

[英]C#: do enums cast themselves as strings or integers as appropriate in the context

If I have the enum: 如果我有枚举:

public enum VehicleType
{
    Car = 0,
    Boat = 1,
    Bike = 2,
    Spaceship = 3
}

and I then do: 然后我做:

int X = 10;
VehicleType vt = (VehicleType)2;
X = X + vt;
Console.WriteLine("I travel in a " + vt + " with " + X + " people.");

What should the output be in C#? C#中的输出应该是什么?

In X = X + vt; X = X + vt; vt will be casted to int. vt将被转换为int。 In "I travel in a " + vt + " with " + X + " people." "I travel in a " + vt + " with " + X + " people." vt will be replaced to vt.ToString(), which will print the name of the enum. vt将被替换为vt.ToString(),它将打印枚举的名称。

An enum's base type is int by default. 枚举的基类型默认为int。 It can also be a byte, sbyte, short, ushort, uint, long, or ulong if explicitly specified. 如果明确指定,它也可以是byte,sbyte,short,ushort,uint,long或ulong。

X = X + vt will error because it needs to be an explicit cast. X = X + vt会出错,因为它需要是一个显式的强制转换。

If it were X += (int)vt; 如果是X += (int)vt; it would be: 这将是:

"I travel in a Bike with 12 people." “我和一个12人的自行车旅行。”

because when using Console.WriteLine all variables' ToString() methods are called so the string representation of the Enum is given (enum is 2, that equates to Bike, so Bike is returned). 因为当使用Console.WriteLine所有变量的ToString()方法都被调用,因此给出了枚举的字符串表示形式(枚举为2,等同于Bike,因此返回Bike)。

They are represented as integers. 它们表示为整数。 I wish they could be represented as objects! 我希望他们可以被表示为对象!

As the others already mentioned you just get an integer. 正如其他人已经提到的那样,你只需要一个整数。

That's because the base-type of an enum is an integer, but this can be changed to any other value type by eg public enum VehicleType : ushort . 这是因为枚举的基类型是一个整数,但是可以通过例如public enum VehicleType : ushort将其更改为任何其他值类型。

To get some better handling with these names the Enum class has some handy functions (like GetName() , IsDefined() or Parse() ). 为了更好地处理这些名称, Enum类有一些方便的函数(如GetName()IsDefined()Parse() )。

Just to answer the question So how can you say that the enum is being represented as an int in what you have just stated? 只是为了回答这个问题那你怎么能说enum在你刚刚陈述的内容中被表示为int? from the comments: Take a look at http://msdn.microsoft.com/en-us/library/sbbt4032.aspx (especially take a decent look into the last example using Flags ). 从评论:看看http://msdn.microsoft.com/en-us/library/sbbt4032.aspx (特别是使用Flags看看最后一个例子)。

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

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