如何在不知道类型</t>的情况下枚举通用List <t>

时间:2009-09-10 04:59:20

标签: c#

我将通用列表传递给函数,我想枚举列表中的对象。如果我能够枚举列表中的项目,我将使用反射来完成其余的工作。

 var Items= new List<String>(){"s1","s2"};
  Enumerate(Items);
  void Enumerate(object items)
  {
        //i know the type so i  can cast and enumerate
        foreach(var item in (List<String>) items)
        {

        }
        // i don't know the type of object in the list
        //Following won't work , can't cast to List<object> 
        foreach (var item in (List<object>) items)
        {

        }
    }

4 个答案:

答案 0 :(得分:9)

我不确定你的最终目标是什么。如果您期望列表,特别是通用列表,为什么不使用泛型方法,如:

void Enumerate<T>(List<T> items)
{
  for(var item in items) 
  {
    //...
  }
}

http://msdn.microsoft.com/en-us/library/twcad0zb(VS.80).aspx更详细地介绍了这一点。

我只是想补充一点,上面的方法本身就违背了for循环的简单目的。同样,我不知道Enumerate在重复项目之上的意图是什么。

答案 1 :(得分:7)

您可以使您的功能通用

public void Enum<T>(List<T> list)
        {
            foreach (T t in list)
            {

            }
        }

答案 2 :(得分:2)

适用的函数版本是:

var Items= new List<String>(){"s1","s2"};
Enumerate(Items);
void Enumerate<T>(List<T> items)
{
    if (typeof(T) == typeof(string))
    {
        //i know the type so i  can cast and enumerate
        foreach(string item in (List<String>) items)
        {

        }
    }
    else
    {
        // i don't know the type of object in the list
        //Following won't work , can't cast to List<object> 
        foreach (T item in items)
        {

        }
    }
}

但这可以更好地写成:

void Enumerate<T>(List<T> items)
{
    foreach (T item in items)
    {
        if (typeof(T) == typeof(string))
        { /* Do something */ }
        else
        { /* Do something else */ }
    }
}

答案 3 :(得分:0)

我有一个静态类,其中有一些utils函数,如列表中的字符串枚举器:

public static string EnumerateStrings<T>(this List<T> items, string separator = "; ")
{
    var result = "";

    if(typeof(T) == typeof(string) && items.SafeAny())
    {
        items.ForEach(str => {
            try
            {
                if (!String.IsNullOrEmpty(str as string))
                {
                    if (!String.IsNullOrEmpty(result))
                        result += separator;
                    result += str;
                }
            }
            catch { }
        });
    }

    return result;
}

使用此功能,您只需使用如下:

string myCarsEnumeration = Cars.Select(ob => ob.Name).ToList().EnumerateStrings();
//output-> Porsche; Lexus; Peugeot

//or

string myCarsEnumeration2 = Cars.Select(ob => ob.Name).ToList().EnumerateStrings(", ");
//output-> Porsche, Lexus, Peugeot

您可以适应更多对象类型。

SafeAny()的代码:

public static bool SafeAny<T>(this IEnumerable<T> list, Func<T, bool> predicate)
{
    return list != null && list.Any(predicate);
}