与枚举互锁.比较交换 [英] Interlocked.CompareExchange with enum

查看:91
本文介绍了与枚举互锁.比较交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Interlocked.CompareExchange 与此枚举:

I'm trying to use Interlocked.CompareExchange with this enum:

public enum State {
    Idle,
    Running,
    //...
}

以下代码无法编译,但这就是我想要做的:

The following code doesn't compile, but that's what I want do do:

if (Interlocked.CompareExchange(ref state, State.Running, State.Idle) != State.Idle) {
    throw new InvalidOperationException("Unable to run - not idle");
}

我可以使用int代替枚举,并使用属性:

Sure I can use a int instead of the enum and use a property:

private int state = (int)State.Idle;
public State { get { return (State)state; } }

然后将枚举转换为整数:

Then cast the enums to a int:

if (Interlocked.CompareExchange(ref state, (int)State.Running, (int)State.Idle) !=  (int)State.Idle) {
    throw new InvalidOperationException("Unable to run - not idle");
}

但是有更好的方法吗?

推荐答案

为简单起见,请::)

不幸的是,C#/.NET将enum视为完整类型,与基本类型部分断开了连接.每次尝试在enum上执行花式"操作时,都会遇到障碍.

Sadly C#/.NET consider enums as full type, partially disconnected from their base type. Every time you try to do something "fancy" on an enum you encounter some barrier.

这篇关于与枚举互锁.比较交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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