将列表转换为列表 ,Type在运行时已知

问题描述 投票:14回答:7

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

我有List<object>和qazxsw poi,它的qazxsw poi可以是qazxsw poi,System.Reflection.FieldFieldType,所以我需要从List<string>转换为那种类型。

List<int>

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

c# system.reflection
7个回答
14
投票

我相信你想要的是:

List<bool>

用法示例:

List<object>

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


更新:由于其他人已经正确地指出这实际上没有返回public static object ConvertList(List<object> value, Type type) { //type may be List<int>, List<bool>, List<string> } (其中T是有问题的类型),因此可能无法完全回答手头的问题,我选择提供更新的答案:

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

如果您不需要转换(因此每个值的类型实际上是正确的,并且您没有字符串中的整数等),则删除var objects = new List<Object> { 1, 2, 3, 4 }; ConvertList(objects, typeof(List<int>)).Dump(); 标志和关联的块。


示例:List<T>


10
投票

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

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 });
}

6
投票

不确定这是否有帮助,但你能使用Linq Cast吗?

performConversion

1
投票

试试这个:

https://dotnetfiddle.net/nSFq22

呼叫:

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;
}

1
投票
List<object> theList = new List<object>(){ 1, 2, 3};
List<int> listAsInt = theList.Cast<int>();

要么

public static List<T> ConvertList<T>(List<object> list)
{
    List<T> castedList = list.Select(x => (T)x);
    return castedList;
}

1
投票
List<object> myList = new List<object> {"test", "foo", "bar"};
List<string> stringList = ConvertList<string>(myList);

0
投票
 public static object ConvertList<T>(List<object> value) where T : class
    {
        var newlist = value.Cast<T>().ToList();
        return newlist;
    }
© www.soinside.com 2019 - 2024. All rights reserved.