是否可以在.Net中将整数枚举设置为任意值

bpe*_*kes 2 c# wcf enums

出于某种原因HttpResponseMessageProperty,我用于将特定HTTP响应代码返回给客户端使用HttpStatusCode枚举.此枚举不包括422,它不包含在枚举中.是否有任何方法可以使用整数设置枚举,因为这是它的内涵?

Dai*_*Dai 6

是的,这是可能的-内部的enum值就是一个整数,你可以"逼"的枚举值有一个无效值和CLR将继续其快乐的方式.

例如:

enum Foo {
   Bar = 1,
   Baz = 2
}

void Test() {
    Foo foo; // as Foo is a value-type and no initial value is set, its value is zero.
    Console.WriteLine( foo ); // will output "0" even though there is no enum member defined for that value

    Foo foo2 = (Foo)200;
    Console.WriteLine( foo2 ); // will output "200"
}
Run Code Online (Sandbox Code Playgroud)

这就是为什么当使用未知来源的枚举值时,您应该始终处理default案例并妥善处理:

public void DoSomethingWithEnum(Foo value) {
    switch( value ) {
        case Foo.Bar:
            // do something
            break;
        case Foo.Baz:
            // do something else
            break;
        default:
            // I like to throw this exception in this circumstance:
            throw new InvalidEnumArgumentException( "value", (int)value, typeof(Foo) );
    }
}
Run Code Online (Sandbox Code Playgroud)