开发者

Creating array of unknown type. C#

开发者 https://www.devze.com 2023-02-20 18:01 出处:网络
While using reflection in C#, you\'re expected to pass an object[] of the parameters that are cast later on, I have a gui that lets the user input the parameters values in. I know what type of input t

While using reflection in C#, you're expected to pass an object[] of the parameters that are cast later on, I have a gui that lets the user input the parameters values in. I know what type of input they are expected to input, int, string, float, instance of custom object, etc... In the case of the argument being an array of some type, int[] foo[], its lets the user construct an array of that type, and add/remove elements.

What I don't know is how I can use the information (i know the type of the data is type t.) How can I construct an array t[], so that when its given to 开发者_如何转开发invoke, it can convert to that array type.

For example right now if i have a function that requires an array of integers as an argument, i am currently passing an object[] with another object[] inside it that is filled with integers, but you can't just cast object[] to int[] so the invoke fails.

I can not write a switch case as it's not possible to predict all possible types it could be (instances of some other class defined in a loaded dll, for example)


Are you looking for Array.CreateInstance? That's useful if you only know the type dynamically. If you know it statically but within a generic method, you can just use new T[10] or whatever the type parameter name is.


This does not answer the question but I felt it might be an advice worth mentioning.

If it is a method which can be called by passing an array of int as well as array of object it seems that you are implementing a type-free behaviour which can be expressed by generics.

I suggest to change it to a generic method using IEnumerable<T>. Of course, IEnumerable<T> cannot be accessed by index (while array can) but not sure this is what you really need there.

In conjunction with MakeGenericType, it can give you the flexbility you need.

0

精彩评论

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