简体   繁体   中英

Implicit/Explicit casting operator from/to generic type

I'm trying to cast a generic type to a fixed one.
The following is what I expect to work, but there is a fundamental flaw in it.

public class Wrapper<T>
{
    public T Value;

    static public implicit operator TypeWithInt(Wrapper<int> wrapper)
    {
        return new TypeWithInt(wrapper.Value);
    }

    static public implicit operator TypeWithFloat(Wrapper<float> wrapper)
    {
        return new TypeWithFloat(wrapper.Value);
    }

    static public implicit operator TypeWithDouble(Wrapper<double> wrapper)
    {
        return new TypeWithDouble(wrapper.Value);
    }
}

The above code doesn't compile with the following error:

User-defined conversion must convert to or from the enclosing type

As Wrapper<int> is different from Wrapper<T> it'll never work, because Wrapper<int> isn't the enclosing type.

So my question is: How can I make this casting work? Is there a way?

Your object model is a bit nonsensical because the .NET type system only considers at most 2 types at a time:

/* type 1 (int) */ int a = "abc" /* type 2 (string) */;

Yet you're trying to force another type in the middle which doesn't mesh. This isn't a limitation of the type conversion process, but instead, a limitation of the language. Every assignment (the phase at which implicit type conversions are enforced) can have at most 2 active parties, the left ( int in the example above) and the right ( string in the example above). Cascading implicit casts are not supported and would likely be really hard to code for.

The only possible solution I see to your problem would be to make this transition more visible to your user and add ToInt , ToFloat methods on Wrapper<T> to allow it to do its job.

Another point of interest might be the performance impact for doing this... the net result of your proposed wrapper is a boxing operation which may lead to unfortunate performance if you're working with a fair load. The alternative would be to rearchitect your application to be less type specific. Doing so would likely also eliminate the issue you're currently facing.

您可以将强制类型转换添加到抽象的非泛型基类中,并使泛型类继承它。

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