简体   繁体   中英

Bridge method with a generic interface to a number of overloaded methods

In my code I am doing conversions from one hierarchy of types into another. I have a set of overloaded methods:

Type1 ToInternalObject(OtherType1 obj);
Type2 ToInternalObject(OtherType2 obj);
//etc.

To make it easier to work with these methods I wanted to create a generic interface: T ToInternalObject<T>(BaseOtherType obj) , but I got already stuck on the case when the type is double :

    public static T ToInternalObject<T>(object obj)
    {
        if (typeof (T) == typeof (double))
        {
            return (T) 5.0;
        }
        throw new Exception("Type is not handled yet");
    }

The compilation error is: Error 140 Cannot convert type 'double' to 'T' . How can I get it to work?

双播应起作用:

return (T) (object) 5.0;

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