c# - Type.GetMethod with a Generic overload - Get Generic MethodInfo without looping through all Methods

标签 c# reflection methodinfo

<分区>

我有两个功能:

  1. public void DeleteRecord(int id);
  2. public T DeleteRecord<T>(int id);

下面是我尝试动态调用泛型方法的方法:

MethodInfo method = typeof(DAL).GetMethod("DeleteRecord", new[] { typeof(int) });
MethodInfo generic = method.MakeGenericMethod(returnType);
object o = generic.Invoke(null, new object[] { dbname, spname, expandoAsDictionary });

第一行抛出一个异常,因为它发现了一个不明确的定义。有什么办法可以得到 MethodInfo不使用 GetMethods 的通用方法并遍历要求 IsGenericMethod 的结果?

编辑: 请删除“重复”,因为两个建议的答案要么通过内部循环(GetMethods().Select...)解决这个问题,要么甚至不解决重载问题。

最佳答案

也许不是您问题的确切解决方案,但也许您会对这个解决方案感到满意:

var generic = typeof(BadFoo).GetMethods().FirstOrDefault(p => p.IsStatic == true && p.Name == "DeleteRecord" && p.ReturnType == typeof(Int32));

我以为方法会有一个“全名”,所以 GetMethod() 可以调用一个全名来获取唯一的方法。但是方法中除了名称之外没有其他属性。

关于c# - Type.GetMethod with a Generic overload - Get Generic MethodInfo without looping through all Methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16793385/

相关文章:

c# - MVVM 会阻止 Visual Studio Designer 显示 xaml 的能力吗?

java try catch block 无法使用反射工作 - 不知道为什么,也可能是线程错误

c# - 来自 Expression 的 PropertyInfo 是否等于来自 GetProperties() 的 PropertyInfo

c# - 将类方法转换为IL并在运行时执行

c# - 通过继承判断两个 MethodInfo 实例是否代表同一个(非虚)方法

c# - 如何使用 Playwright 获得下拉列表的选定选项

c# - tfs 站点服务器中出现 "Value cannot be null. Parameter name: key"问题

c# - 在 C# 中将未知参数/返回类型作为参数的传递方法

c# - 如何将文本框值分配给gridview

java - 在 Java10 中用什么代替 `defineClass`?