如何在C#中使用泛型参数调用泛型方法?

6
我想知道如何在C#中使用反射来调用以下方法:
public static List<T> GetAllWithChildren<T>
    (this SQLiteConnection conn, Expression<Func<T, bool>> filter = null, bool recursive = false) 
    where T
    #if USING_MVVMCROSS: new() #else : class #endif
    {
    }

我的当前代码是:

MethodInfo methodInfo = typeof(ReadOperations).GetMethod("GetWithChildren", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
Type predicateType = predicate.GetType();
MethodInfo genericMethod = methodInfo.MakeGenericMethod(predicateType);
Type[] genericArgumentsType = genericMethod.GetGenericArguments();
Debug.WriteLine("Arguments Number:" + genericArgumentsType.Count());
int count = 0;
foreach (Type ga in genericArgumentsType)
{
    Console.WriteLine(count++ + " " + ga.GetType());
}
Object[] genericArguments = { conn, predicate, true };
genericMethod.Invoke(conn, genericArguments);

返回结果:

返回的参数数量为1...,但我不知道为什么系统会返回这个数字。

调用方法时出现参数数量不正确的错误。

欢迎提供任何帮助!


Generic arguments 的数量为一个 (T)。 参数 的数量为 3 (SQLiteConnection connExpression<Func<T, bool>> filterbool recursive)。 您可以通过调用 GetParameters 来获取这些参数。 - D Stanley
请注意,predicateType 将是 Expression<Func<T, bool>>,这不是调用 MakeGenericMethod 时使用的正确类型。 - D Stanley
3个回答

2

您正在使用 Predicate 的泛型参数来使该方法具有泛型性。这意味着:

Expression<Func<T, bool>> 的泛型参数将是 Func<T, bool>,而这不是您要标记该方法的实际类型。请更新以下行:

Type predicateType = predicate.GetType();
MethodInfo genericMethod = methodInfo.MakeGenericMethod(predicateType);

To

Type parameterType = predicate.Parameters[0].Type;
MethodInfo genericMethod = methodInfo.MakeGenericMethod(parameterType);

这将为您提供来自 Func<T,bool>T 类型。现在它应该按预期工作。
以上更改基于您的谓词是 Expression<Func<T, bool>> 类型的假设。如果谓词是 Func<T, bool>,则可以像下面这样获取 parameterType:
Type parameterType  = predicate1.GetType().GetGenericArguments()[0];

1
每次我看到MakeGenericMethod,我就想起了绿巨人HULK SMASH。Microsoft需要修复这个疯狂的API。 - Chris Marisic

1
您正在使用GetWithChildren进行调用,而不是GetAllWithChildren。

0

你的通用方法是扩展方法...请更改下面的代码并重试

MethodInfo methodInfo = typeof(**SQLiteConnection**).GetMethod("GetAllWithChildren", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接