繁体   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