【发布时间】:2014-07-17 09:08:54
【问题描述】:
在我的代码中,我正在进行从一种类型层次结构到另一种类型的转换。我有一组重载方法:
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'。我怎样才能让它工作?
【问题讨论】: