C#中的枚举如何重载一个运算符? [英] How do I overload an operator for an enumeration in C#?
问题描述
我有一个枚举类型,我想定义>,<,> =和< =运算符。我知道这些操作符是在枚举类型的基础上创建的(根据文档),但是我想要明确定义这些操作符(为了清楚,控制,知道如何做到这一点...)
$ b $我希望我可以这样做:
public enum SizeType
{
Small = 0,
Medium = 1,
Large = 2,
ExtraLarge = 3
}
public SizeType operator>(SizeType x,SizeType y )
{
}
但这似乎不工作(意外的toke)...这可能吗?似乎应该是因为有隐含定义的操作符。任何建议?
你不能这样做。您只能为您定义的类和结构体提供重载运算符,至少有一个参数应该是类或结构本身的类型。也就是说,你可以声明一个重载的加法运算符,它将 MyClass
添加到 MyEnum
你不能用两个 MyEnum
值来实现。
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)
{
}
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?
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屋!