简体   繁体   中英

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. It has worked great. It works just fine when I try to convert an Object (of type List<string> ) back to a List<string> . However, when I try to convert an Object to be a IList<string> , it fails.

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<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? 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 . If the object is actually an IList<string> , you can use an is type pattern to check it:

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

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