将List <object>转换为List <Type>,Type在运行时已知

Rus*_*yev 14 c# system.reflection

我正在实现某种反序列化,并在下一个问题上挣扎:

我有List<object>System.Reflection.Field,这是FieldType可以List<string>,List<int>或者List<bool>,所以我需要从转换List<object>到该类型.

public static object ConvertList(List<object> value, Type type)
{
   //type may be List<int>, List<bool>, List<string>
}
Run Code Online (Sandbox Code Playgroud)

我可以单独编写每个案例,但应该有更好的方法使用反射.

Ric*_*ban 14

我相信你想要的是:

public static object ConvertList(List<object> value, Type type)
{
    var containedType = type.GenericTypeArguments.First();
    return value.Select(item => Convert.ChangeType(item, containedType)).ToList();
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

var objects = new List<Object> { 1, 2, 3, 4 };

ConvertList(objects, typeof(List<int>)).Dump();
Run Code Online (Sandbox Code Playgroud)

我不确定这是多么有用......它突出了我猜的疯狂有用的Convert.ChangeType方法!


更新:由于其他人已经正确地指出这实际上没有返回List<T>(其中T是有问题的类型),因此可能无法完全回答手头的问题,我选择提供更新的答案:

public static object ConvertList(List<object> items, Type type, bool performConversion = false)
{
    var containedType = type.GenericTypeArguments.First();
    var enumerableType = typeof(System.Linq.Enumerable);
    var castMethod = enumerableType.GetMethod(nameof(System.Linq.Enumerable.Cast)).MakeGenericMethod(containedType);
    var toListMethod = enumerableType.GetMethod(nameof(System.Linq.Enumerable.ToList)).MakeGenericMethod(containedType);

    IEnumerable<object> itemsToCast;

    if(performConversion)
    {
        itemsToCast = items.Select(item => Convert.ChangeType(item, containedType));
    }
    else 
    {
        itemsToCast = items;
    }

    var castedItems = castMethod.Invoke(null, new[] { itemsToCast });

    return toListMethod.Invoke(null, new[] { castedItems });
}
Run Code Online (Sandbox Code Playgroud)

如果您不需要转换(因此每个值的类型实际上是正确的,并且您没有字符串中的整数等),则删除该performConversion标志和关联的块.


示例:https://dotnetfiddle.net/nSFq22


Gui*_*ume 10

该类型仅在运行时已知,因此我认为泛型方法不是可行的方法

public static object ConvertList(List<object> value, Type type)
{
   IList list = (IList)Activator.CreateInstance(type);
   foreach (var item in value)
   {
      list.Add(item);
   }
   return list;
}
Run Code Online (Sandbox Code Playgroud)


DLe*_*Leh 6

不知道这是否有帮助,但是您可以使用Linq Cast吗?

List<object> theList = new List<object>(){ 1, 2, 3};
List<int> listAsInt = theList.Cast<int>();
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的解决方案,但它并没有回答最初的问题——类型在运行时是已知的,你会如何处理它? (4认同)
  • 为什么这没有得到更多的支持?这似乎是最简单、易于管理且干净的解决方案! (2认同)