How to apply InterLocked.Exchange for Enum Types in C#?

前端 未结 5 925
难免孤独
难免孤独 2021-02-12 22:39
public enum MyEnum{Value1, Value2}  
class MyClass 
{ 
    private MyEnum _field;   
    public MyEnum Field  // added for convenience
    {
        get { return _field;         


        
5条回答
  •  -上瘾入骨i
    2021-02-12 23:04

    Is there any better way for this problem?

    If you need to use Interlocked.Exchange then this is the best way, in fact I think it is the only way to Exchange an enum.

    The reason you get the compiler error is that the compiler thinks you want to use Exchange, but T needs to be a reference type for this to work, since you are not using a reference type it fails. So, the best work around is to cast to an int as you have done, and thus force the compiler to use the non-generic Exchange(int, int).

提交回复
热议问题