创建未知类型的数组。 C# [英] Creating array of unknown type. C#

查看:64
本文介绍了创建未知类型的数组。 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然在C#中使用反射,但是您希望传递稍后投射的参数的object [],但我有一个gui,可以让用户输入参数值。我知道它们是什么类型的输入预期输入,整数,字符串,浮点数,自定义对象的实例等。。。如果参数是某种类型的数组,则int [] foo []可以让用户构造该类型的数组,并添加/删除元素。

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.

我不知道如何使用信息(我知道数据的类型为t。)构造一个数组t [],以便在调用它时可以将其转换为该数组类型。

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.

例如,如果我现在有一个需要整数数组作为参数,我当前正在传递一个object [],其中带有另一个用整数填充的object [],但是您不能仅将object []转换为int [],因此调用失败。

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.

我无法编写一个切换用例,因为它不可能预测所有可能的类型(例如,在加载的dll中定义的某些其他类的实例)

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)

推荐答案

您是否正在寻找 Array.CreateInstance ?如果您只动态地知道类型 ,这很有用。如果您是静态地但在通用方法内知道它,则可以只使用 new T [10] 或任何类型参数名称。

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.

这篇关于创建未知类型的数组。 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆