枚举到布尔转换问题
我有以下枚举:
public enum MyEnum
{
MyTrue,
MyFalse
}
我希望最终能够使用这样的简单行自动将我的枚举转换为布尔值:
MyEnum val = MyEnum.MyTrue;
bool IsThisTrue = val;
目前,我必须这样做:
bool IsThisTrue = val == MyEnum.MyTrue;
是否有某种机制可以应用于我的枚举允许本机枚举->布尔转换?我想知道类型转换器的某些变体是否是我需要的。
谢谢
编辑:我的自定义枚举是有原因的。由于这些属性最终都绑定到属性网格,因此我们建立了机制将所有自定义枚举绑定到资源文件中的多语言字符串。我们需要将我们使用的所有枚举都放在特定的命名空间中,因此需要“MyEnum”类。
I have the following enumeration:
public enum MyEnum
{
MyTrue,
MyFalse
}
And I'd like to eventually be able to automatically convert my enumeration to a boolean value, with a simple line like this:
MyEnum val = MyEnum.MyTrue;
bool IsThisTrue = val;
Currently, I have to do this:
bool IsThisTrue = val == MyEnum.MyTrue;
Is there some mechanism I can apply to my enumeration to allow for native enum->bool casting? I'm wondering if some variant of a typeconverter is what I need or not.
Thanks
Edit: There is a reason for my custom enumeration. Since this properties are all eventually bound to a property grid, we have mechanisms put in place to bind all of our custom enumerations to multi-lingual strings in resources files. We need all of the enum's we're using to be in a specific namespace, hence the "MyEnum" class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该行仅适用于隐式静态转换运算符(或者可能是更令人困惑的 true() 运算符,但在野外很少见)。您无法在枚举上定义运算符,因此最终答案是:不。
不过,您可以在
MyEnum
上编写一个扩展方法来返回true
或false
。那么你可以使用 bool IsThisTrue = val.Value();
That line would work only with an implicit static conversion operator (or maybe the more-confusing
true()
operator, but that is rarely seen in the wild). You cannot define operators on enums, so ultimately the answer is: no.You could, however, write an extension method on
MyEnum
to returntrue
orfalse
.then you can use
bool IsThisTrue = val.Value();
编写一个像这样的扩展方法:
然后忘记它
Write an extension method like this:
and forget about it
试试这个:
然后:
Try this:
then: