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

man*_*der 20 c# reflection

我有一个要求,我需要在我的类中获取构造函数的变量名称.我尝试使用c#reflection,但constructorinfo没有提供足够的信息.因为它只提供参数的数据类型,但我想要名称,例如

class a
{    
    public a(int iArg, string strArg)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

M4N*_*M4N 38

如果你调用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));
    }
}
Run Code Online (Sandbox Code Playgroud)

以上样本打印:

Param 0 is named iArg and is of type System.Int32
Param 1 is named strArg and is of type System.String
Run Code Online (Sandbox Code Playgroud)


Pil*_*anz 5

我刚检查了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);  
 }
Run Code Online (Sandbox Code Playgroud)

您可以查看msdn GetParameters()以获取任何其他信息.

心连心