繁体   English   中英

返回基类型(struct)的泛型强制转换方法

[英]Generic cast method returning base type (struct)

我想编写一个方法,将值(对象)转换为基本类型(如string,int,double等)。 我在一个在对象上映射DataRows的例程中使用此方法。

我写了这个:

public static T CastObjectToBasicType<T>(DataRow row, string column)
    where T : struct
{
    object cellValue = row[column];

    if (typeof(T) == typeof(string))
        return ToString(cellValue);

    if (typeof(T) == typeof(int) || typeof(T) == typeof(int?))
        return ToInt(cellValue);

    if (typeof(T) == typeof(bool) || typeof(T) == typeof(bool?))
        return ToBool(cellValue);

    if (typeof(T) == typeof(double) || typeof(T) == typeof(double?))
        return ToDouble(cellValue);

    if (typeof(T) == typeof(decimal) || typeof(T) == typeof(decimal?))
        return ToDecimal(cellValue);

    if (typeof(T) == typeof(DateTime) || typeof(T) == typeof(DateTime?))
        return ToDateTime(cellValue) ;

     throw new ArgumentException("T not supported");
}

其中ToString,ToBool,ToDouble等方法是将输入转换为desidered类型的简单方法。

上面的代码没有编译; 问题是我无法将结果转换为类型T,因为T是一个结构而且我无法使用(用于exaple)

return ToDouble(obj) as T;

也不

return (T) ToDouble(obj);

如果我替换该条款

where T : struct

where T : class

然后我无法使用int,bool,double等调用方法...作为T因为它们不是类。

我不知道是否有办法实现这一目标; 另一种方法是直接调用ToBool,ToInt等简单方法,而不是从泛型方法中传递,但我更喜欢使用单个强制转换方法。

有什么我能做的吗? 任何帮助将不胜感激,也是替代品。

提前致谢。

这是因为,就编译器所知, T和例如DateTime之间没有可能的转换。

尝试将DateTime上传到唯一的祖先DateTimeT有共同点 - object - 然后向下转换回T

return (T) (object) ToDouble(obj);

除非你真的想限制某些东西(接口,类,结构等),否则你不需要指定where T子句。 在这里你没有,所以只需删除where子句

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM