c#中构造函数参数的名称

本文关键字:参数 构造函数 | 更新日期: 2023-09-27 18:01:20

我有一个要求,我需要在我的类中获得构造函数的变量名称。我尝试使用c#反射,但constructorinfo没有给出足够的信息。因为它只提供参数的数据类型,但我想要的名称,ex

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

现在我想要"iArg"answers"strArg"

谢谢

c#中构造函数参数的名称

如果您调用ConstructorInfo.GetParameters(),那么您将返回一个ParameterInfo对象的数组,该数组具有包含参数名称的Name属性。

有关更多信息和示例,请参阅此MSDN页面。

下面的示例打印类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