簡體   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?

我正在使用Convert.ChangeType(object, Type)方法將對象轉換為它們的類型。 它工作得很好。 當我嘗試將Object (類型為List<string> )轉換回List<string> <string> 時,它工作得很好。 但是,當我嘗試將Object轉換為IList<string>時,它失敗了。

問題:當我嘗試將應為IList IList ,它失敗並顯示錯誤消息“對象必須實現 IConvertible”

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

任何人都知道如何成功地將 object 轉換回其原始類型的 IList... 或者有人知道如何將原本是 IList 的 object 轉換為列表嗎? 要么工作。

下面的代碼解決了我的問題:

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

無需使用Convert.ChangeTypedynamic 如果 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