在C#构造函数的参数名称 [英] Name of the constructor arguments in c#
问题描述
我在,我需要得到构造函数的变量的名称在我班上的要求。
我想它使用C#反射,但constructorinfo不给足够的信息。因为它仅提供了参数的数据类型,但我想的名字,前
I've a requirement in which i need to get the variables names of the constructor in my class. I tried it using c# reflection, but constructorinfo does not give sufficient information. As it only provides the datatype of the parameters but i want the names, ex
Class a
{
public a(int iArg, string strArg)
{
}
}
现在我想iArg和strArg
Now i want "iArg" and "strArg"
感谢
推荐答案
如果你调用 ConstructorInfo.GetParameters()
,那么你会得到的ParameterInfo
对象,其中有一个名称
包含参数的name属性。
If you call ConstructorInfo.GetParameters()
, then you will get back an array of ParameterInfo
objects, which has a Name
property containing the name of the parameter.
请参阅this MSDN页面的更多信息和示例。
See this MSDN page for more information and a sample.
有关A类的构造函数的每个参数下面的示例打印的信息:
The following sample prints information about each parameter of class A's constructor:
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));
}
}
以上样本打印:
The above sample prints:
Param 0 is named iArg and is of type System.Int32
Param 1 is named strArg and is of type System.String
这篇关于在C#构造函数的参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!