简体   繁体   中英

Determining the number of parameters accepted by a method

Is it possible to get the number of parameters accepted by a method and then access the values of these parameters individually? I want to create a method which concatenates the values of all the parameters of a method, except the last parameter. However, the number of parameters and the name of the parameters depend on the method being accessed.

Is it possible to do something similar to the following pseudo-code?

StringBuilder string = new StringBuilder();

for(int i = 0; i < Method.Parameters.Count - 1; i++)
{
     string.Append(Method.Parameters[i].Value);
}

Thank you very much :)

这样做:

Type.GetType("MyClassType").GetMethod("foo").GetParameters().Length;

If you have a method like

void Foo(string s, int x, int y, bool flag)

then you don't need to determine the number of arguments programmatically – you already know that there are 4 arguments.

{
    StringBuilder sb = new StringBuilder().Append(s)
                                          .Append(x)
                                          .Append(y);
}

If you want the method accept any number of arguments, then you can use the params keyword to define your method as follows:

void Baz(params object[] args)

The arguments are passed as an array to your method, so you can determine the number of arguments from the array length:

{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < args.Length - 1; i++)
    {
        sb.Append(args[i]);
    }
}

Usage:

Baz("xyzzy", 42, 0, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM