将DataTable列类型传递给泛型方法<t> </t>

时间:2011-08-25 19:09:23

标签: c# .net generic-type-argument

我有一个声明为

的方法
public static T GetValidatedValue<T>(string param)
{
   do something here and return object of type T...;
}

通常我称之为var somnum = GetValidatedValue(“14”); 并且期望sumNum为数字或者如果将无效值传递为“0”

我现在的问题是我需要将一个datatabel列类型作为“T”传递给此方法

类似的东西:

dr[col] = GetValidatedValue <typeof(dr[col])>(dr[col].ToString());

这将无法编译

它基本上是我在某处找到的两(2)种方法的组合(甚至可能在这个网站上),并根据我的需要进行修改

public static T GetValidatedValue<T>(string param)
{
    return TryParse<T>(param);
}

private static T TryParse<T>(string inValue)
{
    var converter = TypeDescriptor.GetConverter(typeof(T));

    try
    {
        return (T)converter.ConvertFromString(null, CultureInfo.InvariantCulture,     inValue);
    }
    catch
    {
        return default(T);
    }
}

任何人都可以了解我做错了什么......

2 个答案:

答案 0 :(得分:0)

KISS方法怎么样:

static readonly Dictionary<Type, object> defaultMap = new Dictionary<Type, object>()
        {
            { typeof(DateTime), DateTime.MinValue },
            { typeof(Int32), 0},
            { typeof(String), ""}
            /* etc etc etc*/
        };

private static void SetDefault(Type type, ref object value)
{
    if(value == DBNull.Value || value == null)
        value = defaultMap[type];
}

然后你就叫它:

SetDefault(col.DataType, ref dr[col]);

答案 1 :(得分:0)

当你知道编译时的类型是什么时,泛型真的很有用,在这种情况下你可以像这样调用你的方法:

GetValidatedValue<int>(dr[col].ToString());

但是,在我看来,在编译时你实际上并不知道类型,所以泛型只会妨碍。尝试实现方法的非泛型版本,如下所示:

public static object GetValidatedValue(string param, Type type)
{
    return TryParse(param, type);
}

private static object TryParse(string inValue, Type type)
{
    var converter = TypeDescriptor.GetConverter(type);

    try
    {
        return converter.ConvertFromString(null, CultureInfo.InvariantCulture, inValue);
    }
    catch
    {
        return default(T);
    }
}

这样你就可以这样称呼它:

GetValidatedValue<int>(dr[col].ToString(), dr[col].GetType());

(虽然我必须承认,将某些内容转换为字符串然后再将其转换回原始类型似乎是不必要的开销。)

更新

现在我已经更好地了解了您要执行的操作,但上述方法无效,因为如果dr[col]nullDbNull将不会有任何类型,如果它是DbNull,它将具有public static object GetValidatedValue(string param, Type type) { return param == null || param == DBNull.Value ? Activator.CreateInstance(type); } 类型。除非您有其他方法来确定应该存储在该列中的数据类型,否则它将无法正常工作。当然,如果您可以找出应该在哪种数据类型,那么获取默认值将非常简单:

{{1}}
相关问题