我需要在类中获取构造函数的变量名称。
我使用C#反射进行了尝试,但是Constructorinfo没有提供足够的信息。因为它仅提供参数的数据类型,但我想要名称,例如

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

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

谢谢

最佳答案

如果调用ConstructorInfo.GetParameters(),则将返回ParameterInfo对象的数组,该数组具有Name属性,其中包含参数名称。

有关更多信息和示例,请参见this MSDN page

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

关于c# - C#中的构造函数参数名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6606515/

10-12 14:41
查看更多