代码之家  ›  专栏  ›  技术社区  ›  Grzenio

具有到多个重载方法的通用接口的Bridge方法

  •  0
  • Grzenio  · 技术社区  · 10 年前

    在我的代码中,我正在进行从一个类型层次结构到另一个类型的转换。我有一组重载方法:

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

    为了更容易使用这些方法,我想创建一个通用接口: T ToInternalObject<T>(BaseOtherType obj) ,但当类型为 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");
        }
    

    编译错误为: Error 140 Cannot convert type 'double' to 'T' 。我怎样才能让它工作?

    1 回复  |  直到 10 年前
        1
  •  2
  •   Selman Genç    10 年前

    双铸件应工作:

    return (T) (object) 5.0;