簡體   English   中英

c# 中的構造函數名稱 arguments

[英]Name of the constructor arguments in c#

我有一個要求,我需要在我的 class 中獲取構造函數的變量名稱。 我嘗試使用 c# 反射,但 constructorinfo 沒有提供足夠的信息。 因為它只提供參數的數據類型,但我想要名稱,例如

class a
{    
    public a(int iArg, string strArg)
    {
    }
}

現在我想要“iArg”和“strArg”

謝謝

如果您調用ConstructorInfo.GetParameters() ,那么您將返回一個ParameterInfo對象數組,該數組具有包含參數名稱的Name屬性。

有關更多信息和示例,請參閱此 MSDN 頁面

以下示例打印有關 class A 的構造函數的每個參數的信息:

public class A
{
    public A(int iArg, string strArg)
    {
    }
}

....

public void PrintParameters()
{
    var ctors = typeof(A).GetConstructors();
    // assuming class A has only one constructor
    var ctor = ctors[0];
    foreach (var param in ctor.GetParameters())
    {
        Console.WriteLine(string.Format(
            "Param {0} is named {1} and is of type {2}",
            param.Position, param.Name, param.ParameterType));
    }
}

上面的示例打印:

Param 0 is named iArg and is of type System.Int32
Param 1 is named strArg and is of type System.String

我剛剛檢查了 MSDN 以了解您的問題。 正如我所見,任何ConstructorInfo實例都可能為您提供方法GetParameters() 此方法將返回一個ParameterInfo[] - 並且任何ParameterInfo都有一個屬性Name 所以這應該可以解決問題

 ConstructorInfo ci = ...... /// get your instance of ConstructorInfo by using Reflection
 ParameterInfo[] parameters = ci.GetParameters();

 foreach (ParameterInfo pi in parameters)
 {
      Console.WriteLine(pi.Name);  
 }

您可以檢查msdn GetParameters()以獲取任何其他信息。

hth

暫無
暫無

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

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