views:

34

answers:

3

case as followed:

in the project a

public class X1
{
  public string Name="X1";
}

public class X2
{
  public string GetName(string name)
  {
   return "";
  }

  public string GetName(string name,ref X1 x1)
  {
   return "";
  }
}

question:

how to get 'GetName' MethodInfo by reflection's getmethd function in other project

+1  A: 

Two options:

  • You can call typeof(X2).GetMethods() and then just filter out the ones with the wrong names. This can sometimes be easier than calling GetMethod() providing the exact data.
  • You can use Type.MakeByRefType to specify the ref parameter type in a call to Type.GetMethod(). So in this case you'd use (assuming you want the second of the methods shown):

    MethodInfo method = typeof(X2).GetMethod
        ("GetName", new [] { typeof(string), typeof(X1).MakeByRefType() });
    
Jon Skeet
thanks, it is good method
Luis Zhan
A: 
var method1 = typeof(X2).GetMethod("GetName", new[] { typeof(string) });
var method2 = typeof(X2).GetMethod("GetName", new[] { typeof(string), typeof(X1).MakeByRefType() });
Darin Dimitrov
A: 

you can do this

foreach (var mi in typeof(X2).GetMethods())
{
    if (mi.Name.Equals("GetName"))
    {
        Console.WriteLine("Method Name : {0}", mi.Name);
        var miPerms = mi.GetParameters();
        if (miPerms.Count() > 0)
            Console.WriteLine("Params : {0}", miPerms.Select(p => p.ParameterType + " " + p.Name).Aggregate((a, b) => a + "," + b));
    }
}
IBhadelia