如何在 C# 中为枚举重载运算符? [英] How do I overload an operator for an enumeration in C#?

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

问题描述

我有一个枚举类型,我想定义 ><>=<= 运算符.我知道这些运算符是基于枚举类型隐式创建的(根据 文档)但我想明确定义这些运算符(为了清晰,为了控制,知道如何做,等等......)

我希望我能做这样的事情:

公共枚举SizeType{小 = 0,中 = 1,大 = 2,超大 = 3}公共 SizeType 运算符 >(SizeType x, SizeType y){}

但这似乎不起作用(意外令牌")......这可能吗?似乎应该如此,因为存在隐式定义的运算符.有什么建议吗?

解决方案

你不能那样做.您只能为您定义的类和结构提供重载运算符——并且至少其中一个参数应该是类或结构本身的类型.也就是说,您可以声明一个重载的加法运算符,该运算符将一个 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 token") ... 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屋!

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