Explicit & Implicit Operator with Numeric Types & unexpected results

心不动则不痛 提交于 2019-12-11 02:46:18

问题


I have never done any extensive work with overloading operators, especially the implicit and explicit conversions.

However, I have several numeric parameters that are used frequently, so I am creating a struct as a wrapper around a numeric type to strongly type these parameters. Here's an example implementation:

public struct Parameter
{
    private Byte _value;
    public Byte Value { get { return _value; } }

    public Parameter(Byte value)
    {
        _value = value;
    }

    // other methods (GetHashCode, Equals, ToString, etc)

    public static implicit operator Byte(Parameter value)
    {
        return value._value;
    }
    public static implicit operator Parameter(Byte value)
    {
        return new Parameter(value);
    }

    public static explicit operator Int16(Parameter value)
    {
        return value._value;
    }
    public static explicit operator Parameter(Int16 value)
    {
        return new Parameter((Byte)value);
    }
}

As i was experimenting with my test implementation to get a hang of the explicit and implicit operators, I tried to explicitly cast a Int64 to my Parameter type and to my surprised it did not throw an exception, and even more surprising, it just truncated the number and moved on. I tried excluding the custom explicit operator and it still behaved the same.

public void TestCast()
{
    try
    {
        var i = 12000000146;
        var p = (Parameter)i;
        var d = (Double)p;

        Console.WriteLine(i);   //Writes 12000000146
        Console.WriteLine(p);   //Writes 146
        Console.WriteLine(d);   //Writes 146
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);  //Code not reached
    }
}

So I repeated my experiment with a plain Byte in place of my struct and has the same exact behavior, so obviously this is expected behavior, but I thought an explicit cast that results in a lose of data would throw an exception.


回答1:


When the compiler is analyzing an explicit user-defined conversion it is allowed to put an explicit built-in conversion on "either side" (or both) of the conversion. So, for example, if you have a user-defined conversion from int to Fred, and you have:

int? x = whatever;
Fred f = (Fred)x;

then the compiler reasons "there is an explicit conversion from int to Fred, so I can make an explicit conversion from int? to int, and then convert int to Fred.

In your example, there is a built-in explicit conversion from long to short, and there is a user-defined explicit conversion from short to Parameter, so converting long to Parameter is legal.

The same is true of implicit conversions; the compiler may insert built-in implicit conversions on either side of a user-defined implicit conversion.

The compiler never chains two user defined conversions.

Building your own explicit conversions correctly is a difficult task in C#, and I encourage you to stop attempting to do so until you have a thorough and deep understanding of the entire chapter of the specification that covers conversions.

For some interesting aspects of chained conversions, see my articles on the subject:

http://blogs.msdn.com/b/ericlippert/archive/2007/04/16/chained-user-defined-explicit-conversions-in-c.aspx

http://blogs.msdn.com/b/ericlippert/archive/2007/04/18/chained-user-defined-explicit-conversions-in-c-part-two.aspx




回答2:


This goal:

so I am creating a struct as a wrapper around a numeric type to strongly type these parameters

And this code:

public static implicit operator Byte(Parameter value)
{
    return value._value;
}
public static implicit operator Parameter(Byte value)
{
    return new Parameter(value);
}

Are in total contradiction. By adding 2-way implicit operators you annul any type-safety the wrapper might bring.

So drop the implicit conversions. You can change them to explicit ones.



来源:https://stackoverflow.com/questions/8526547/explicit-implicit-operator-with-numeric-types-unexpected-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!