簡體   English   中英

如何使用反射C#獲取構造函數泛型參數類型

[英]How to get Constructor Generic parameter type using reflection c#

大家好,謝謝。 我有一個類和一個參數化構造函數,我想讀取構造函數參數類型。 說吧

Class A
{    
    public A(Helper help)
    {
       // code
    }
}

在上面的代碼中,我們可以使用以下代碼讀取構造函數:

Type ClassType = typeof(A);
ConstructorInfo[] Constructors = ClassType.GetConstructors();
foreach (ConstructorInfo constInfo in Constructors)
{
    if (constInfo.GetParameters().Count() > 0)
    {
        RefNames = new List<string>();
        foreach (ParameterInfo parameters in constInfo.GetParameters())
        {
             Type newType = parameters.ParameterType;
        }
    }
}

因此,在newType中,我將獲得“ Helper”類的Type,但我希望從通用接口輸入Type。 例如

Class A
{    
    public A(IHelper<Helper> help)
    {
       // code
    }
}

//凡是從IHelper介面繼承的Helper類別現在,我想輸入IHerper介面的類型,例如Helper的類型。

提前致謝。

不問你為什么這樣做,但是可以通過訪問ParameterInfo GenericTypeArguments屬性來獲取使用的通用類型:

Type newType = parameters.ParameterType.GenericTypeArguments.First();

暫無
暫無

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

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