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

时间:2016-01-28 15:25:48

标签: c# generics reflection sqlite-net

我想知道如何在C#中使用反射来调用以下方法:

include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|237|note: 'const opts_t& threaded_alignment::align_scan_struct::opts' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|238|note: 'const std::vector<char*>& threaded_alignment::align_scan_struct::mesh_names' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|239|note: 'const std::vector<std::vector<corr_t> >& threaded_alignment::align_scan_struct::corrs' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|240|note: 'const std::vector<trimesh::Vec<3u, float> >& threaded_alignment::align_scan_struct::targets' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|241|note: 'const std::vector<bool>& threaded_alignment::align_scan_struct::use_points' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|242|note: 'const std::vector<float>& threaded_alignment::align_scan_struct::confidence' should be initialized|
include\global_reg.h|279|error: uninitialized reference member in 'struct threaded_alignment::align_scan_struct'|
include\global_reg.h|244|note: 'const std::vector<trimesh::TriMesh::Face>& threaded_alignment::align_scan_struct::all_faces' should be initialized|

我目前的代码是:

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
    {
    }

返回的参数数量为1 ......这是错误的,但我不知道为什么系统会将此数字返回给我。

调用方法失败,参数数量错误。

欢迎任何帮助!

3 个答案:

答案 0 :(得分:1)

你用GetWithChildren而不是GetAllWithChildren调用它。

答案 1 :(得分:1)

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

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

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

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

这会从T为您提供Func<T,bool>的类型。现在它应该按预期工作。

以上更改基于您的谓词属于Expression<Func<T, bool>>类型的假设。如果谓词是Func<T, bool>,则可以像下面那样获取parameterType:

Type parameterType  = predicate1.GetType().GetGenericArguments()[0];

答案 2 :(得分:0)

您的通用方法是扩展方法....更改以下代码并重试

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