[英]C# Get Delegate from MethodInfo
I have a problem with this code :我对这段代码有问题:
public static Delegate[] ExtractMethods(object obj)
{
Type type = obj.GetType();
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
Delegate[] methodsDelegate = new Delegate[methods.Count()];
for (int i = 0; i < methods.Count(); i++)
{
methodsDelegate[i] = Delegate.CreateDelegate(null, methods[i]);
}
return methodsDelegate;
}
at Delegate.CreateDelegate
delegate type most drived but I call this method for several objects.在Delegate.CreateDelegate
委托类型最受驱动,但我为几个对象调用此方法。 How to get delegate type ?如何获得委托类型?
It worked for me.它对我有用。 [ https://stackoverflow.com/a/16364220/1559611 ] [ https://stackoverflow.com/a/16364220/1559611 ]
public static Delegate[] ExtractMethods(object obj)
{
Type type = obj.GetType();
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
Delegate[] methodsDelegate = new Delegate[methods.Count()];
for (int i = 0; i < methods.Count(); i++)
{
methodsDelegate[i] = CreateDelegate(obj , methods[i]);
}
return methodsDelegate;
}
public static Delegate CreateDelegate(object instance, MethodInfo method)
{
var parameters = method.GetParameters()
.Select(p => Expression.Parameter(p.ParameterType, p.Name))
.ToArray();
var call = Expression.Call(Expression.Constant(instance), method, parameters);
return Expression.Lambda(call, parameters).Compile();
}
Use MethodInfo.DeclaringType
使用MethodInfo.DeclaringType
Type type = methods[0].DeclaringType;
you will have to be bit careful if you are using inheritance.如果您使用继承,您将不得不小心。
Also have a look at MethodInfo.ReflectedType
也看看MethodInfo.ReflectedType
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.