gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:09:10 26 4
gpt4 key购买 nike

出于某种原因,我用来向客户端返回特定 HTTP 响应代码的 HttpResponseMessageProperty 使用了 HttpStatusCode 枚举。此枚举不包括 422,它不包含在枚举中。有什么方法可以使用整数来设置枚举吗?

最佳答案

是的,这是可能的 - 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) );
}
}

关于c# - .Net 中是否可以将整数枚举设置为任意值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32057052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com