c#中构造函数参数的名称
我有一个要求,我需要在我的类中获取构造函数的变量名称。 我尝试使用c#reflection,但constructorinfo没有提供足够的信息。 因为它只提供参数的数据类型,但我想要名称,例如
class a { public a(int iArg, string strArg) { } }
现在我想要“iArg”和“strArg”
谢谢
如果调用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()以获取任何其他信息。
心连心