Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

reflection - Name of the constructor arguments in c#

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)
    {
    }
}

Now i want "iArg" and "strArg"

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

See this MSDN page for more information and a sample.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...