创建未知类型的数组。 C#
在 C# 中使用反射时,您需要传递稍后转换的参数的 object[],我有一个 gui,可以让用户输入参数值。我知道他们需要输入什么类型的输入、int、string、float、自定义对象的实例等...如果参数是某种类型的数组,int[] foo[],它允许用户构造该类型的数组,并添加/删除元素。
我不知道如何使用这些信息(我知道数据的类型是 t 类型。)如何构造一个数组 t[],以便当它被调用时,它可以转换为该数组类型。
例如,现在如果我有一个需要整数数组作为参数的函数,我当前正在传递一个 object[] ,其中包含另一个充满整数的 object[] ,但你不能只强制转换 object[]到 int[] 因此调用失败。
我无法编写 switch case,因为不可能预测它可能的所有可能类型(例如,在加载的 dll 中定义的其他类的实例)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否在寻找
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 usenew T[10]
or whatever the type parameter name is.这并没有回答问题,但我觉得这可能是一个值得一提的建议。
如果它是一个可以通过传递
int
数组以及object
数组来调用的方法,那么您似乎正在实现可以表达的无类型行为通过泛型。我建议使用
IEnumerable
将其更改为通用方法。当然,IEnumerable
无法通过索引访问(而数组可以),但不确定这是否是您真正需要的。与 MakeGenericType 结合使用,它可以为您提供灵活性你需要。
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 ofobject
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.