【发布时间】:2017-09-20 17:28:07
【问题描述】:
在 C# 中是否可以将数组类型转换为单数类型 - 以与 Activator.CreateInstance 一起使用。以此为例:
void Main()
{
var types = new[] { typeof(ExampleClass), typeof(ExampleClass[]) };
var objects = new List<object>();
foreach (var type in types)
{
// possibly convert type here? (from array to singular - type[] to type)
Debug.WriteLine($"{type}");
objects.Add(Activator.CreateInstance(type));
}
}
// Define other methods and classes here
public class ExampleClass
{
public int X;
public int Y;
}
得到以下输出:
【问题讨论】:
-
你想退回什么?一个元素为零的数组?一个元素的数组?数组元素类型的实例?还有什么?
-
如果我错了,请纠正我,但您的代码与您的问题无关。您正在询问转换数组类型,但在代码中您只是试图创建一个新数组(使用反射),但由于您没有向数组构造函数提供参数而失败 - 您的数组的大小'正在尝试创建。