首页 文章

避免模糊的匹配异常

提问于
浏览
91

我通过反射调用一个静态方法Parse,因为我不知道编译时对象的类型(我知道,它有一个Parse方法,带一个字符串) .

但是,我得到了一个模糊的匹配异常,大概是因为有很多重载的Parse方法,每个方法都占用一个对象(string,int,double等) .

如何在我的方法调用中更具体,以确保我到达正确的方法(Parse(string s))并且不抛出异常 .

我的代码如下所示:

Type returnType = p.PropertyType;
object value = returnType.GetMethod("Parse").Invoke(null, new string[] { "1" });

2 回答

  • 156
    if (assembly != null)
    {
      List<System.Reflection.MethodInfo> mInfo = new List<System.Reflection.MethodInfo>();
      Type myType = null;
    
      foreach (Type item in assembly.GetTypes())
      {
        mInfo.Clear();
        mInfo = item.GetMethods().ToList();
        foreach (System.Reflection.MethodInfo item2 in mInfo)
        {
          if (item2.Name == methodName)
          {
            Method = item2;
            break;
          }
        }
      }
    
      stateInstance = Activator.CreateInstance(myType);
    }
    return Method;
    
  • -3

    使用this重载并使用

    returnType.GetMethod("Parse", new [] {typeof(string)})
    

相关问题