开发者

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

I have a Dictionary object where the Keys are of type string and the Values are of type object because they are extracted from a file where the data type (for column) might differ.

Dictionary<string, object[]> lfileContent;

I would like to get the type of every array and casting the type. Of course I cannot do it while they are in the Dictionary but when I extract each Value to use them. For instance (I use a pseudocode C# using a logical approach):

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

I would like to make three questions:

1) When I get the elements from the file and store them as object, will they keep the information that reflection uses to get their type?

2) If (1) does not apply, shall I use reflection to get their type when I extract them from the file (before inserting as object in the Dictionary)?

3) How can I make such casting by using refl开发者_JAVA百科ection?

Thanks

Francesco


You don't need Reflection, but the object will retain the type info. To cast the object to a type you have to tell it which type at compile time, you could use Reflection to dynamically manipulate the object, but that's different than casting it as a type. I would use something like this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜