简体   繁体   中英

C# Method overloading resolution and user-defined implicit conversions

I try to find some information about method overloading resolution in case of presence of user-defined implicit conversions and about conversions priority.

This code:

class Value
{
    private readonly int _value;
    public Value(int val)
    {
        _value = val;
    }

    public static implicit operator int(Value value)
    {
        return value._value;
    }

    public static implicit operator Value(int value)
    {
        return new Value(value);
    }
}

class Program
{
    static void ProcessValue(double value)
    {
        Console.WriteLine("Process double");
    }

    static void ProcessValue(Value value)
    {
        Console.WriteLine("Process Value");
    }

    static void Main(string[] args)
    {
        ProcessValue(new Value(10));
        ProcessValue(10);
        Console.ReadLine();
    }
}

Produces output:

Process Value
Process Value

So, It looks like compiler chosen user-defined conversion instead of built-in implicit conversion from int to double (built-in conversion is implicit due to info from this page https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit-numeric-conversions-table ).

I tried to find something about this in specification, but with no success.

Why compiler selected ProcessValue(Value value) instead of ProcessValue(double value)

In this case, the conversion between int -> double takes lower precedence because a user-defined implicit conversion between int -> Value exists.

See: User-defined operator implementations always take precedence over predefined operator implementations .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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