具有未知项目类型的Foreach列表

Mur*_*tný 5 c#

我需要通过List.我事先不知道哪种类型的元素List包含我作为对象获得的List.

void anyMethod(object listData, Func<object, string> callback)
{
    foreach (object item in (List<object>)data)
    {
        string value = callback(item);
        doSomething(value)
    }
};
...
List<MyObject> myList = something();
anyMethod(myList, obj => (MyObject)obj.Name)
...
List<AnotherObject> myList = somethingAnother();
anyMethod(myList, obj => (AnotherObject)obj.foo + (AnotherObject)obj.bar)
...
Run Code Online (Sandbox Code Playgroud)

当进程DataSource时,我需要他作为DropDownList做的事情.谢谢你的帮助.

Jam*_*iec 6

你可以试试这个:

void anyMethod(object listData, Func<object, string> callback)
{
    IEnumerable enumerable = listData as IEnumerable;
    if(enumerable == null)
        throw new InvalidOperationException("listData mist be enumerable");
    foreach (object item in enumerable.OfType<object>())
    {
        string value = callback(item);
        doSomething(value)
    }
};
Run Code Online (Sandbox Code Playgroud)

但是,如果您实际上使用强类型列表(例如List<YourType>)调用此方法,则可以更好地使用泛型:

void anyMethod<T>(IEnumerable<T> listData, Func<T, string> callback)
{
    foreach (T item in listData)
    {
        string value = callback(item);
        doSomething(value)
    }
};
Run Code Online (Sandbox Code Playgroud)

哪个更清洁.