System.Reflection.AmbigouslyMatchException:“发现不明确的匹配。”

问题描述 投票:0回答:2

我正在尝试从方法

MethodInfo
获取
TableExists<T>
,这样我就可以用类型来调用它。

该方法在

OrmLiteSchemaApi
类中声明。有 2 个重载:

public static bool TableExists<T>(this IDbConnection dbConn)
{
  // code omitted
}

public static bool TableExists(this IDbConnection dbConn, string tableName, string schema = null)
{
  // code omitted
}

我正在尝试像这样获得

MethodInfo

var tableMethod = typeof(OrmLiteSchemaApi).GetMethod("TableExists");

但它会产生异常:

System.Reflection.AmbigouslyMatchException:“发现不明确的匹配。”

我只能找到一个与此相关的老问题,建议传递一个空对象数组作为参数,但这似乎不适用于.net core。

我想我需要指定具体的过载,但我不确定具体如何。

如何获得

MethodInfo

c# .net-core
2个回答
30
投票

您可以使用

GetMethods
(复数!)来获取所有匹配方法的数组,然后查找具有
IsGenericMethod
的方法:

var tm = typeof(OrmLiteSchemaApi)
        .GetMethods()
        .Where(x => x.Name == "TableExists")
        .Where(x => x.IsGenericMethod);
        .FirstOrDefault();

我建议使用参数说明符,因为它会给你一个对象,如果出现任何问题,你可以在调试时单步执行。


7
投票

仅当您正在寻找不带参数的函数时,传递空对象数组才有效。相反,您需要使用 GetMethod 的不同重载,将参数类型指定为类型数组。这样你就可以通过指定它应该查找哪些类型的参数来告诉它要获取哪个引用。

© www.soinside.com 2019 - 2024. All rights reserved.