C# 将数组类型转换为单数
在C#中,是否可以将数组类型转换为单数-用于Activator.CreateInstance。以此为例:C# 将数组类型转换为单数,c#,activator,C#,Activator,在C#中,是否可以将数组类型转换为单数-用于Activator.CreateInstance。以此为例: void Main() { var types = new[] { typeof(ExampleClass), typeof(ExampleClass[]) }; var objects = new List<object>(); foreach (var type in types) { // possibly convert
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;
}
void Main()
{
var types=new[]{typeof(ExampleClass),typeof(ExampleClass[])};
var objects=新列表();
foreach(类型中的变量类型)
{
//可能在此处转换类型?(从数组到单数-类型[]到类型)
Debug.WriteLine($“{type}”);
Add(Activator.CreateInstance(type));
}
}
//在此处定义其他方法和类
公共类示例类
{
公共int X;
公共智力;
}
获取以下输出:
如果我正确理解您的问题,您可能希望通过反射使用Type.GetElementType()实现类似的功能
static void Main(string[] args)
{
var types = new[] { typeof(ExampleClass), typeof(ExampleClass[]) };
var objects = new List<object>();
foreach (var type in types)
{
var typeInstance = type.GetElementType();
if (typeInstance != null)
{
Debug.WriteLine($"{typeInstance}");
objects.Add(Activator.CreateInstance(typeInstance));
}
else
{
objects.Add(Activator.CreateInstance(type));
}
}
}
public class ExampleClass
{
public int X;
public int Y;
}
static void Main(字符串[]args)
{
var types=new[]{typeof(ExampleClass),typeof(ExampleClass[])};
var objects=新列表();
foreach(类型中的变量类型)
{
var typeInstance=type.GetElementType();
if(typeInstance!=null)
{
WriteLine($“{typeInstance}”);
Add(Activator.CreateInstance(typeInstance));
}
其他的
{
Add(Activator.CreateInstance(type));
}
}
}
公共类示例类
{
公共int X;
公共智力;
}
如果我正确理解了你的问题,你想得到数组的基类型,对吗?使用类型的IsArray
属性应该很容易,只需像下面这样检查列表中的每个条目:
private static Type GetTypeOrElementType(Type type)
{
if (!type.IsArray)
return type;
return type.GetElementType();
}
顺便说一句,如果您想创建该特定类型的新数组,可以使用Array.CreateInstance
而不是Activator.CreateInstance
找到以下方法:
void Main()
{
var types = new[] { typeof(ExampleClass), typeof(ExampleClass[]) };
var objects = new List<object>();
foreach (var type in types)
{
Debug.WriteLine($"{type}");
objects.Add(type.IsArray
? Activator.CreateInstance(type, 1)
: Activator.CreateInstance(type));
}
}
// Define other methods and classes here
public class ExampleClass
{
public int X;
public int Y;
}
void Main()
{
var types=new[]{typeof(ExampleClass),typeof(ExampleClass[])};
var objects=新列表();
foreach(类型中的变量类型)
{
Debug.WriteLine($“{type}”);
添加(type.IsArray
?Activator.CreateInstance(类型,1)
:Activator.CreateInstance(类型));
}
}
//在此处定义其他方法和类
公共类示例类
{
公共int X;
公共智力;
}
您希望返回什么?零元素数组?有一个元素的数组?数组元素类型的实例?还有什么吗?如果我错了,请纠正我,但你的代码与你的问题没有什么关系。您要求转换数组类型,但在代码中,您只是尝试创建一个新数组(使用反射),这是失败的,因为您没有向数组构造函数提供参数—您尝试创建的数组的大小。是否可能重复?