如何在C#中将InterLocked.Exchange应用于枚举类型?

如何在C#中将InterLocked.Exchange应用于枚举类型?

问题描述:

public enum MyEnum{Value1, Value2}  
class MyClass 
{ 
    private MyEnum _field;   
    public MyEnum Field  // added for convenience
    {
        get { return _field; }  
        set { Interlocked.Exchange(ref _field, value); // ERROR CS0452  }
    }  
} 

可以通过以下方式解决:

could be solved with:

 public enum MyEnum{Value1, Value2}  
 public class MyClass2  
 {  
   private int _field;  //change to int
   public MyEnum Field  // added for convenience
   { 
    get { return (MyEnum)_field; }
    set { System.Threading.Interlocked.Exchange(ref _field, (int)value); }
   }  
 }

有没有更好的方法来解决这个问题?

Is there any better way for this problem?

有没有更好的方法来解决这个问题?

Is there any better way for this problem?

如果您需要使用 Interlocked.Exchange ,那么这是最好的方法,实际上,我认为这是交换枚举的唯一方法.

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.

出现编译器错误的原因是,编译器认为您想使用 Exchange< T> ,但是T必须是此类型的引用类型,因为您没有使用引用类型失败.因此,最好的解决方法是像完成操作一样将其强制转换为 int ,从而强制编译器使用非通用的 Exchange(int,int).

The reason you get the compiler error is that the compiler thinks you want to use Exchange<T>, 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).