简体   繁体   中英

Cast dynamic to List<T>

private static void GetData()
{
   dynamic dynamicList =FetchData();
   FilterAndSortDataList(dynamicList);
}

private static void FilterAndSortDataList<T>(List<T> dataList)
{
    ...
}

I am getting a runtime binding error when I call FilterAndSortDataList. Is there a way to cast my dynamicList to List<T> at runtime?

Note that FetchData() is implimented by plugins, so I don't know in advance what the type T is.

I see no reason why it should fail, unless FetchData is improper data.

Possibility I: FetchData is returning null, and hence the type parameter cannot be figured out (null has no type in C#).

Possibility II: FetchData is not returning a proper List<T> object.

I would redesign the thing like:

private static void GetData()
{
   dynamic dynamicList = FetchData();

   if (dynamicList is IEnumerable) //handles null as well
       FilterAndSortDataList(Enumerable.ToList(dynamicList));

   //throw; //better meaning here.
}

It checks whether the returned type is IEnumerable (hoping that it is some IEnumerable<T> - we cant check if it is IEnumerable<T> itself since we dont have T with us. Its a decent assumption) in which case we convert the obtained sequence to List<T> , just to be sure we are passing a List<T> . dynamic wont work with extension methods, so we have to call Enumerable.ToList unfortunately. In case dynamicList is null or not an enumerable it throws which gives it better meaning than some run time binding error.

Is there a way to cast my dynamicList to List at runtime

I don't know why you declare it as dynamic when it has to be a List<T> , but I'm guessing it is because you don't know what T is. If you did , you could just directly cast it:

private static void GetData()
{
   dynamic dynamicList = new List<string> ();
   FilterAndSortDataList((List<string>)dynamicList);
}

private static void FilterAndSortDataList<T>(List<T> dataList)
{
    ...
}

but obviously that could fail at runtime.

Another option might be to make GetData generic as well:

private static void GetData<T>()
{
   List<T> list = new List<T>();
   FilterAndSortDataList(list);
}

private static void FilterAndSortDataList<T>(List<T> dataList)
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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