C# 获取Enumerable.First()的MethodInfo与Enumerable.OfType()的MethodInfo?
要获取我们可以使用的信息,请使用:C# 获取Enumerable.First()的MethodInfo与Enumerable.OfType()的MethodInfo?,c#,linq,reflection,C#,Linq,Reflection,要获取我们可以使用的信息,请使用: typeof(System.Linq.Enumerable).GetMethod("OfType", new Type[] { typeof(IEnumerable) }) 对于的MethodInfo,我们可以使用类似的: typeof(System.Linq.Enumerable).GetMethod("Sum", new Type[] { typeof(IEnumerable<int>) }) 当方法重载时,例如使用谓词,例如getMe
typeof(System.Linq.Enumerable).GetMethod("OfType", new Type[] { typeof(IEnumerable) })
MethodInfo
,我们可以使用类似的:
typeof(System.Linq.Enumerable).GetMethod("Sum", new Type[] { typeof(IEnumerable<int>) })
MethodInfo
调用变得更加笨拙*:
typeof(Enumerable).GetMember(“First”).OfType()。其中(m=>m.GetParameters()。Length==1)。First()
可枚举
中定义的扩展方法中,它们扩展了IEnumerable
、IEnumerable
,或IEnumerable
的特定专业,如IEnumerable
为什么调用typeof(Enumerable).GetMethod(“Reverse”、新类型{typeof(IEnumerable)}
和typeof(Enumerable).GetMethod(“First”、新类型[]{typeof(IEnumerable)}
返回null
而不是MethodInfo
-对象?前两种扩展方法与后两种扩展方法有什么区别
*:请参见和 签名:
public static IEnumerable<TResult> OfType<TResult>(
this IEnumerable source
)
类型的采用IEnumerable
<代码>反向
采用IEnumerable
,而不是IEnumerable
Sum
需要IEnumerable
,可以作为参数类型传入
获取MethodInfo
的另一种类型安全的方法是:
public MethodInfo GetMethod(Expression<Action> e)
{
var methodCall = e.Body as MethodCallExpression;
if (methodCall.Method.IsGenericMethod)
return methodCall.Method.GetGenericMethodDefinition();
return methodCall.Method;
}
var method = GetMethod(() => Enumerable.Empty<int>().First());
var overLoadedMethod = GetMethod(() => Enumerable.Empty<int>().First(a => true));
签名:
public static IEnumerable<TResult> OfType<TResult>(
this IEnumerable source
)
类型的采用IEnumerable
<代码>反向
采用IEnumerable
,而不是IEnumerable
Sum
需要IEnumerable
,可以作为参数类型传入
获取MethodInfo
的另一种类型安全的方法是:
public MethodInfo GetMethod(Expression<Action> e)
{
var methodCall = e.Body as MethodCallExpression;
if (methodCall.Method.IsGenericMethod)
return methodCall.Method.GetGenericMethodDefinition();
return methodCall.Method;
}
var method = GetMethod(() => Enumerable.Empty<int>().First());
var overLoadedMethod = GetMethod(() => Enumerable.Empty<int>().First(a => true));
public MethodInfo GetMethod(Expression<Action> e)
{
var methodCall = e.Body as MethodCallExpression;
if (methodCall.Method.IsGenericMethod)
return methodCall.Method.GetGenericMethodDefinition();
return methodCall.Method;
}
var method = GetMethod(() => Enumerable.Empty<int>().First());
var overLoadedMethod = GetMethod(() => Enumerable.Empty<int>().First(a => true));
GetMethod(() => ((MyThing)null).DoSomething());