【问题标题】:how to get method by reflection's getmethod techenology and method is overrided and paramters has reference self-defined paramter如何通过反射的getmethod技术获取方法,方法被覆盖,参数有引用自定义参数
【发布时间】:2011-03-08 18:45:56
【问题描述】:

案例如下:

在项目中

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 "";
  }
}

问题:

如何在其他项目中通过反射的getmethd函数获取'GetName' MethodInfo

【问题讨论】:

  • 对标题中的术语进行吹毛求疵 - 该方法是重载,而不是覆盖

标签: c# reflection getmethod


【解决方案1】:

两种选择:

  • 您可以拨打typeof(X2).GetMethods(),然后过滤掉名字错误的人。这有时比致电GetMethod() 提供准确数据更容易。
  • 您可以使用Type.MakeByRefType 在对Type.GetMethod() 的调用中指定ref 参数类型。所以在这种情况下你会使用(假设你想要显示的第二种方法):

    MethodInfo method = typeof(X2).GetMethod
        ("GetName", new [] { typeof(string), typeof(X1).MakeByRefType() });
    

【讨论】:

    【解决方案2】:
    var method1 = typeof(X2).GetMethod("GetName", new[] { typeof(string) });
    var method2 = typeof(X2).GetMethod("GetName", new[] { typeof(string), typeof(X1).MakeByRefType() });
    

    【讨论】:

      【解决方案3】:

      你可以这样做

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-06
        • 2010-09-16
        • 2016-04-25
        • 1970-01-01
        • 2016-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多