【问题标题】:Is it possible in .Net to set integer enum to arbitrary value.Net 中是否可以将整数枚举设置为任意值
【发布时间】:2015-08-17 18:15:46
【问题描述】:

出于某种原因,我用来向客户端返回特定 HTTP 响应代码的 HttpResponseMessageProperty 使用了 HttpStatusCode 枚举。此枚举不包括 422,它不包含在枚举中。有没有办法使用整数来设置枚举,因为这就是它的底层内容?

【问题讨论】:

  • 是的,只需转换整数值,例如:HttpStatusCode code = (HttpStatusCode)422; 不保证这可能会对您的程序产生不利影响。 (例如,也许某处有验证/检查/逻辑期望它是命名的枚举值之一)

标签: c# wcf enums


【解决方案1】:

是的,这是可能的 - 在内部 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"
}

这就是为什么在处理未知来源的枚举值时,您应该始终处理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) );
    }
}

【讨论】:

  • 题外话,但既然你提到了,throw new InvalidEnumArgumentException("value", (int)value, typeof(Foo)); 对调试无效枚举值更有用。
【解决方案2】:

您可以将任何数字转换为枚举,前提是该枚举具有相同的基本结构(通常是int:

response.StatusCode = (HttpStatusCode)422;

【讨论】:

    【解决方案3】:

    是的,你可以有任何你想要的值(只要它在枚举的基本类型的范围内,通常是 int):

    HttpStatusCode value = (HttpStatusCode)422;
    

    【讨论】:

      猜你喜欢
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多