简体   繁体   English

创建未知类型的数组。 C#

[英]Creating array of unknown type. C#

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.在 C# 中使用反射时,您需要传递稍后投射的参数的 object[],我有一个 gui 可以让用户输入参数值。我知道他们希望输入什么类型的输入、int、string、float、自定义对象的实例等...在参数是某种类型的数组的情况下,int[] foo[],它允许用户构造该类型的数组,并添加/删除元素。

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.我不知道的是如何使用这些信息(我知道数据的类型是类型 t。)我如何构造一个数组 t[],以便在给定调用时,它可以转换为该数组类型。

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.例如,现在如果我有一个需要整数数组作为参数的函数,我目前正在传递一个对象 [],其中另一个对象 [] 里面装满了整数,但你不能只转换对象 []到 int[] 所以调用失败。

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)我无法编写 switch case,因为无法预测所有可能的类型(例如,在加载的 dll 中定义的其他类的实例)

Are you looking for Array.CreateInstance ?您在寻找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.如果您静态地知道它但在泛型方法中,您可以只使用new T[10]或任何类型参数名称。

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.如果它是一种可以通过传递int数组和object数组来调用的方法,那么您似乎正在实现一种可以由泛型表示的无类型行为。

I suggest to change it to a generic method using IEnumerable<T> .我建议使用IEnumerable<T>将其更改为通用方法。 Of course, IEnumerable<T> cannot be accessed by index (while array can) but not sure this is what you really need there.当然, IEnumerable<T>不能通过索引访问(而数组可以),但不确定这是否是您真正需要的。

In conjunction with MakeGenericType , it can give you the flexbility you need.MakeGenericType结合使用,它可以为您提供所需的灵活性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM