如何在C#中将InterLocked.Exchange应用于枚举类型? [英] How to apply InterLocked.Exchange for Enum Types in C#?

查看:67
本文介绍了如何在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).

这篇关于如何在C#中将InterLocked.Exchange应用于枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆