문제

Quoted from C# From CLR

The CLR specification mandates that operator overload methods be public and static methods.

I checked ECMA-335, but couldn't find any evidence.

So far I know it is true for C# and F#. Is it true for all CLS-compliant language?

도움이 되었습니까?

해결책

It looks like it's not really required to be public, but making it non-static is problematic at execution time. I experimented by starting with this code:

using System;

class Oddity
{
    public static Oddity operator+(Oddity x, Oddity y)
    {
        Console.WriteLine("Adding oddities");
        return null;
    }
}

class Test
{    
    static void Main()
    {
        var x = new Oddity();
        var y = new Oddity();
        var z = x + y;
    }
}

... and then running it through ildasm, changing things, then using ilasm and running the result.

  • Changing the accessibility modifier to assembly (equivalent to internal): all was fine
  • Changing the accessibility modifier to private: it assembled (which surprised me) but then failed at execution time:

    Unhandled Exception: System.MethodAccessException: Attempt by method 'Test.Main()' to access method 'Oddity.op_Addition(Oddity, Oddity)' failed.
    at Test.Main()

  • Removing the static part: it assembled (again, surprising me) but then failed at execution time:

    Unhandled Exception: System.MissingMethodException: Method not found: 'Oddity Oddity.op_Addition(Oddity, Oddity)'.
    at Test.Main()

I suspect these really should be caught at assembly time, but as languages are only expected to produce operators which are public and static, the validator is a little lax.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top