c#从泛型函数中获取一个空列表而不是null

时间:2014-02-13 09:03:25

标签: c# list function generics return-type

我有一个泛型函数,其中T可以是从int到Dictionary字符串,字符串或List int的任何东西 如果我使用 T tmpOb =默认值(T); 并返回tmpOb稍后返回int返回0,这很好 但对于一个List int,它返回null,但如果我可以得到一个空的List int,那将非常酷。

我可以做类似

的事情
public static T ConvertAndValidate<T>(string bla)
{
    T tmpOb = default(T);
    if (typeof(T) == typeof(List<int>))
    {
        tmpOb = new List<int>();
    }
    else if(typeof(T) == typeof(List<string>))
    {
        tmpOb = new List<string>();
    }

    //Do other generic stuff that could overwrite the value of tmpOb 

    return tmpOb;
}

是他们实现这一目标的任何真正通用方法吗?像

这样的东西
public static T ConvertAndValidate<T>(string bla)
{
    T tmpOb = default(T);
    if (typeof(T) == typeof(List<x>))
    {
        tmpOb = new List<x>();
    }

    //Do other generic stuff that could overwrite the value of tmpOb 
    return tmpOb;
}

3 个答案:

答案 0 :(得分:1)

是的,有一个通用约束:

public static T ConvertAndValidate<T>(string bla)
    where T : new()
{
    T t = new T();
}

答案 1 :(得分:0)

我不完全符合你的要求...... 但是可能的解决方案是分配空列表或空对象或者对于任何值类型,可以使用下面的行

Activator.CreateInstance<T>();

我希望这符合你的目的。

答案 2 :(得分:0)

我也不确定您的需求,但您可以将方法更改为:

    private static T ConvertAndValidate<T>(string bla)
    {
        T ret = default(T);
        if (typeof(System.Collections.IList).IsAssignableFrom(typeof(T)))
        {
            if (typeof(T).GetGenericArguments().Length > 0)
            {
                ret = (T)Activator.CreateInstance(typeof(T));
            }
        }
        return ret;
    }

这将检查它是否是IList以及它是否包含泛型参数。多数民众赞成......

相关问题