GetConstructors不能找到声明的构造函数

本文关键字:构造函数 声明 不能 GetConstructors | 更新日期: 2023-09-27 18:06:54

我正在试验System.Type。在下面的代码中,我对数组类型使用了GetConstructors:

using System;
using System.Reflection;
class Animal 
{
    public Animal (string s)
    {
        Console.WriteLine(s);
    }
}
class Test
{
    public static void Main()
    {
        Type AnimalArrayType = typeof(Animal).MakeArrayType();
        Console.WriteLine(AnimalArrayType.GetConstructors()[0]);
    }
}

输出为:Void .ctor(Int32)。为什么?不应该是Void .ctor(System.string)

GetConstructors不能找到声明的构造函数

您调用.MakeArrayType(),所以您正在对Animal数组进行反射,而不是Animal本身。如果你去掉它,你会得到你想要的构造函数。

Type AnimalArrayType = typeof(Animal);
Console.WriteLine(AnimalArrayType.GetConstructors()[0]);

如果你想获得数组类型的元素类型,你可以这样做:

Type AnimalArrayType = typeof(Animal[]);
Console.WriteLine(AnimalArrayType.GetElementType().GetConstructors()[0]);

为了构造一个所需大小的数组,可以使用:

Type AnimalArrayType = typeof(Animal[]);
var ctor = AnimalArrayType.GetConstructor(new[] { typeof(int) });
object[] parameters = { 3 };
var animals = (Animal[])ctor.Invoke(parameters);