Bri*_*nga 2 c# generics reflection
我正在尝试使用反射来获取类的特定MethodInfo,但我不确定如何区分以下两个方法:
public class Test
{
public IBar<T1> Foo<T1>();
public IBar<T1, T2> Foo<T1, T2>();
}
Run Code Online (Sandbox Code Playgroud)
假设我知道类型参数的数量,我怎样才能获得对不同Foo方法的引用?只是调用typeof(Test).GetMethod("Foo")将抛出一个异常,即方法名称不明确,并且没有要检查的参数数量不同.
您可以获取所有方法,然后根据通用参数计数过滤它们:
typeof(Test).GetMethods()
.First(x => x.Name == "Foo" && x.GetGenericArguments().Length == 2);
Run Code Online (Sandbox Code Playgroud)
请注意,First如果没有满足条件的方法,则方法将抛出异常.如果要避免异常,则可以使用FirstOrDefault并检查null.