簡體   English   中英

GetConstructors找不到聲明的構造函數

[英]GetConstructors doesn't find the declared constructor

我正在嘗試使用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)

你調用了.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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM