簡體   English   中英

使用 C# 中的反射將元素投射到未知類型的數組上

[英]Cast elements on an array of unknown types by using reflection in C#

我有一個字典 object,其中是字符串類型,是 object 類型,因為它們是從數據類型(對於列)可能不同的文件中提取的。

Dictionary<string, object[]> lfileContent;

我想獲取每個數組的類型並轉換類型。 當然,當它們在字典中時我不能這樣做,但是當我提取每個以使用它們時。 例如(我使用邏輯方法使用偽代碼 C#):

ltype = lfileContent["key1"].Value.GetType();
ltype newarray = (ltype) fileContent["key1"].Value;

我想提出三個問題:

1)當我從文件中獲取元素並將它們存儲為object時,它們會保留反射用於獲取其類型的信息嗎?

2)如果(1)不適用,當我從文件中提取它們時(在字典中插入為object之前),我是否應該使用反射來獲取它們的類型?

3)我怎樣才能使用反射進行這種鑄造?

謝謝

弗朗切斯科

您不需要反射,但 object 將保留類型信息。 要將 object 轉換為您必須在編譯時告訴它哪種類型的類型,您可以使用反射來動態操作 object,但這與將其轉換為類型不同。 我會使用這樣的東西:

string[] stringArray = fileContent["Key1"].Value as string[];
if (stringArray != null) {
    // the object is a string[] type, it is safe to use the stringArray variable
}

// and continue for other types that may be stored in the dictionary

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM