简体   繁体   English

C#无法重载+如果第二个参数是枚举

[英]C# Cannot overload + if second parameter is an enum

I have the following signature for overloaded + : 对于重载+我具有以下签名:

    public static double operator +(MyClass x, MyEnum e)

and an expression of the form: 以及以下形式的表达式:

    x.Value = someMyClassValue + MyEnum.X;

The behavior the debugger shows is as if the expression had been: 调试器显示的行为就像表达式已经出现:

    x.Value = MyEnum.X;

The overload never gets called. 重载永远不会被调用。

I also have: 我也有:

    public static double operator +(MyClass x, object o)

but that doesn't get called either for enums, though it does for other cases. 但这对于枚举都不会调用,尽管对于其他情况也是如此。

I also have overloads for string, int, float, double, and they all work perfectly. 我也有字符串,整数,浮点数,双精度数的重载,它们都可以正常工作。 Why is enum a special case, and why the odd behavior? 为什么枚举是一种特殊情况,为什么会有奇怪的行为? Could this be a bug in the Mono compiler? 这可能是Mono编译器中的错误吗?

I'm using Mono 2.10.8.1 on Ubuntu 13.04. 我在Ubuntu 13.04上使用Mono 2.10.8.1。

Afternote 后记

The problem was that I had also defined an implicit cast to int . 问题是我还为int定义了一个隐式转换。 See my answer for details. 有关详细信息,请参见我的答案。

The problem was that I had also defined: 问题是我还定义了:

public static implicit operator int(MyClass o)

The implicit cast takes precedence over the overloaded operator, and the whole addition expression takes the type of the enum. 隐式强制转换优先于重载运算符,整个加法表达式采用枚举的类型。

Since I wanted to keep the implicit cast to int , I adopted this solution: 由于我想将隐式转换保留为int ,因此我采用了以下解决方案:

    public enum MyEnum : ulong

With that, the cast to int no longer takes place. 这样,将不再强制转换为int

The following program demonstrates the problem I was having. 以下程序演示了我遇到的问题。 It's output is "SECOND" instead of "OK". 输出为“ SECOND”而不是“ OK”。

using System;

public class EnumPlus
{
    public enum Constant
    {
        FIRST,
        SECOND
    };

    // if this implicit cast is removed the result is what I expected
    public static implicit operator int(EnumPlus f)
    {
        return 1;
    }

    public static string operator+(EnumPlus o, int i)
    {
        Console.WriteLine("operator + called for int");
        return "BAD";
    }

    public static string operator+(EnumPlus o, Constant Constant)
    {
        Console.WriteLine("operator + called for enum");
        return "OK";
    }

    public static void Main()
    {
        EnumPlus o = new EnumPlus();
        Console.WriteLine(o + Constant.FIRST);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM