简体   繁体   English

使用List <>的Convert.ChangeType上的运行时异常

[英]RunTime exception on Convert.ChangeType with List<>

I am running into a RunTime Exception while trying to run a List (cast as object) through Convert.ChangeType. 我在尝试通过Convert.ChangeType运行列表(作为对象广播)时遇到了运行时异常。 This is basically the setup: 这基本上是设置:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> list = new List<string>{ "1", "2", "3"};
        Utils utils = new Utils();
        utils.ChangeType(list, typeof(List<int>));
        Console.WriteLine("Done!");
    }
}

public class Utils
{
    public object ChangeType(object obj, Type type)
    {
         return Convert.ChangeType(obj, type);
    }
}

Fiddle here . 在这里摆弄。

This generates the following exception: 这将产生以下异常:

Run-time exception (line 19): Object must implement IConvertible.

Stack Trace:

    [System.InvalidCastException: Object must implement IConvertible.]
       at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
       at System.Convert.ChangeType(Object value, Type conversionType)
       at Utils.ChangeType(Object obj, Type type) :line 19
       at Program.Main() :line 10

I have no clue how to fix this. 我不知道如何解决这个问题。 I think I should cast object obj in Utils.ChangeType to a list of a generic type if it is a list, but I cannot get that to work. 我认为我应该将Utils.ChangeType中的对象obj转换为泛型类型的列表(如果它是列表),但是我无法使它正常工作。

Does anyone know how to fix this issue? 有人知道如何解决此问题吗?

I fixed the issue by adding the following check to Utils.ChangeType: 我通过向Utils.ChangeType添加以下检查来解决此问题:

if (IsList(obj))
{
    List<object> objs = ((IEnumerable)obj).Cast<object>().ToList();
    Type containedType = type.GenericTypeArguments.First();
    return objs.Select(item => Convert.ChangeType(item, containedType)).ToList();
}

With IsList being a generic function in Utils to check if object is a List<>. IsList是Utils中的通用函数,用于检查对象是否为List <>。

See the updated fiddle . 请参阅更新的小提琴

As the exception states, the object you are trying to use convert on does not implement IConvertible. 作为异常状态,您尝试在其上使用convert的对象未实现IConvertible。 You are trying to convert a list of strings to a list of ints, and the list type is not implementing the required interface. 您正在尝试将字符串列表转换为整数列表,并且列表类型未实现所需的接口。

String and int types do implement this interface, so you can do it like this: 字符串和整数类型确实实现了此接口,因此您可以这样执行:

  List<string> list = new List<string> { "1", "2", "3" };
  Utils utils = new Utils();
  var result = list.Select(o => (int)Convert.ChangeType(o, typeof(int)));
  Console.WriteLine("Done!");

Or more concisely: 或更简而言之:

  List<string> list = new List<string> { "1", "2", "3" };
  Utils utils = new Utils();
  var result = list.Select(Int32.Parse);
  Console.WriteLine("Done!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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