我想用Interlocked.CompareExchange
與從int繼承,像這樣的枚舉類型:如何將ref [enum type]轉換爲ref int?
public enum MyEnum : int { A, B }
public class MyClass
{
private static readonly MyEnum s_field = MyEnum.A;
public void Foo()
{
if (Interlocked.CompareExchange(ref s_field, MyEnum.B, MyEnum.A) == MyEnum.A)
{
Console.WriteLine("Changed from A to B");
}
}
}
然而,CompareExchange
只引用類型和選擇值類型(見here)的作品。由於MyEnum
是真正的皮膚下面一個int,我想我應該能夠把它作爲一個參考INT:
// should call CompareExchange(ref int, int, int) overload
Interlocked.CompareExchange(ref s_field, (int)MyEnum.B, (int)MyEnum.A);
然而,這似乎並沒有任何工作。我得到以下錯誤:
Error CS1503: Argument 1: cannot convert from 'ref MyEnum' to 'ref int'
鑄造之前,它通過,例如ref (int)s_field
,也沒有幫助。
我該如何解決這個問題?有沒有辦法使用CompareExchange
和枚舉,或者我必須使用整數嗎?
是否有你的工作枚舉任何具體的原因是什麼? 「互鎖」限於數字在這reguas ...你可以使用常量(我知道,...設計氣味,但)? –
@AndreasNiedermair是的,我只是覺得代碼看起來更好用枚舉。 –
你不能做你想做的事情,因爲'Interlocked'沒有提供API的'enum'變種。你必須使用'int'。 – GreatAndPowerfulOz