简体   繁体   English

Convert.ChangeType (Error: Object must implement IConvertible) 当 Dynamically Convert object to IList 失败 为什么?

[英]Convert.ChangeType (Error: Object must implement IConvertible) when Dynamically Convert object to IList fails Why?

I am using the Convert.ChangeType(object, Type) method to convert objects to their types.我正在使用Convert.ChangeType(object, Type)方法将对象转换为它们的类型。 It has worked great.它工作得很好。 It works just fine when I try to convert an Object (of type List<string> ) back to a List<string> .当我尝试将Object (类型为List<string> )转换回List<string> <string> 时,它工作得很好。 However, when I try to convert an Object to be a IList<string> , it fails.但是,当我尝试将Object转换为IList<string>时,它失败了。

Issue: When I try to convert an object which should be of type IList , to IList , it fails with error message 'Object must implement IConvertible'问题:当我尝试将应为IList IList ,它失败并显示错误消息“对象必须实现 IConvertible”

IList<string> myList = new List<string>();
object myObject = myList;
Type myType = typeOf(IList<string>);
Convert.ChangeType(myObject, myType);

Anyone know how to successfully convert an object back to its original type of IList... Or does anyone know how to convert an object which was originally an IList to a List?任何人都知道如何成功地将 object 转换回其原始类型的 IList... 或者有人知道如何将原本是 IList 的 object 转换为列表吗? Either would work.要么工作。

The below code solved my issue:下面的代码解决了我的问题:

// Initial objects (the original IList object ended up as an object plus a Type)
IList<string> stringList = new List<string>(); // dont' have access to this form of the object
object myObject = stringList;
Type originalType = typeof(List<string>);

// Converting object to a List<string>
if(originalType.Name.StartsWith("IList"))
{
  Type myNewList = typeof(List<>);
  Type typeInIList = originalType.GenericTypeArguments[0];
  Type aStringListType = myNewList.MakeGenericType(typeInIList);
  dynamic newStringList = Convert.ChangeType(myObject, aStringListType);
}

There is no need to use Convert.ChangeType , or dynamic .无需使用Convert.ChangeTypedynamic If the object is actually an IList<string> , you can use an is type pattern to check it:如果 object 实际上是IList<string> ,您可以使用is类型模式来检查它:

if (myObject is IList<string> list) {
    // "list" is the converted list
} else {
    // conversion fails
}

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

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