我如何重载运营商在C#中的枚举? [英] How do I overload an operator for an enumeration in C#?

查看:168
本文介绍了我如何重载运营商在C#中的枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举类型,我想定义>,<,> =,和< =运营商。我知道,这些运营商正在implictly枚举类型的基础上创建(根据的文档),但我想显式定义这些运营商(为清楚起见,控制,要知道怎么办呢,等...)

I have an enumerated type that I would like to define the >, <, >=, and <= operators for. I know that these operators are implictly created on the basis of the enumerated type (as per the documentation) but I would like to explictly define these operators (for clarity, for control, to know how to do it, etc...)

我希望我可以做这样的事情:

I was hoping I could do something like:

public enum SizeType
{
    Small = 0,
    Medium = 1,
    Large = 2,
    ExtraLarge = 3
}

public SizeType operator >(SizeType x, SizeType y)
{

}

但是,这似乎并没有工作(意外托克)...这可能吗?现在看来似乎应该是因为有implictly定义操作。有什么建议?

But this doesn't seem to work ("unexpected toke") ... is this possible? It seems like it should be since there are implictly defined operators. Any suggestions?

推荐答案

您不能这样做。你可以只提供重载运算符类和定义结构 - 和参数至少有一个应该是类型的类的或结构本身。也就是说,你的可以的声明重载加法操作,增加了一个 MyClass的 MyEnum ,但你永远无法做到这一点与两个 MyEnum 值。

You can't do that. You can only provide overloaded operators for classes and structs you define -- and at least one of the parameters should be of type of the class or struct itself. That is, you can declare an overloaded addition operator that adds a MyClass to MyEnum but you can never do that with two MyEnum values.

这篇关于我如何重载运营商在C#中的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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