如何设置枚举的数值

How to set an Enum's numeric value

有没有办法设置枚举的基础值(例如通过反射)? 如果设置值没有匹配的枚举条目会发生什么?

奖金:将枚举设置为“无效”值后,对使用枚举的人有何影响?

谢谢!

编辑:(用例) 一个用例是用于测试目的。 假设您有一个协议,其消息类型字段由枚举表示,在协议中作为字节传输。 现在,如果我想测试一些无效的消息类型字段值,也就是未定义因此不属于枚举的一部分,该怎么办。

奖励 2: 如果枚举类型是动态的而不是固定的,那么这个转换看起来会是什么样子。例如。假设您得到一个枚举类型的对象,并希望将其基础值设置为 1。

我会尽量回答所有你的问题

给定

public enum SomeEnum
{
    Bob,
    Blip
}

Is there a way to set the underlying value of an enum

是..

myEnum = (SomeEnum)1; ///  = Blip

And what will happen if there is no matching enum entry for the set value?

没有...

myEnum = 3;

If(myEnum == SomeEnum.Bob)
   // never gets hit

What would be the implications for someone using the enum after it was set to an "invalid" value?

同上

考虑

SomeEnum myEnum;
    
myEnum = (SomeEnum)1;
Console.WriteLine(myEnum);
    
myEnum = (SomeEnum)3;
Console.WriteLine(myEnum);

输出

Blip
3

尽管您可以想象有人范围检查枚举的情况

var myEnum = (SomeEnum)3;

switch (myEnum)
{
    case SomeEnum.Bob:
       break;
    case SomeEnum.Blip:
       break;
    default:
       throw new ArgumentOutOfRangeException();
 }

在这种情况下会抛出异常


Now what if I want to test some message type field values which are invalid, aka not defined and thus not part of the enum.

你可以使用 Enum.IsDefined Method

Returns a Boolean telling whether a given integral value, or its name as a string, exists in a specified enumeration.

例子

if(!Enum.IsDefined(SomeWeirdReflectedType, someValue))
  ...

How would that cast look like if the enum type is dynamic as opposed to fixed

您可以在运行时使用 Enum.ToObject 将整数转换为 enum

Converts a specified integer value to an enumeration member.

例子

var someEnumType = typeof(SomeEnum);

var asd = Enum.ToObject(someEnumType, 1);

Console.WriteLine(asd);
Console.WriteLine(asd.GetType());

输出

Blip
ConsoleApp1.Program+SomeEnum