最近我试图在 WP7 应用程序中做这样的事情
我有课
abstract class A {
//this method has an implementation
protected void DoSomething<T, TKey>(Func<T, TKey> func) { //impl here }
};
我想通过派生类中的反射调用该受保护的方法:
public class B : A {
void SomeMethod(Type tableType, PropertyInfo keyProperty){
MethodInfo mi = this.GetType()
.GetMethod("DoSomething", BindingFlags.Instance | BindingFlags.NonPublic)
.MakeGenericMethod(new Type[] { tableType, keyProperty.GetType() });
LambdaExpression lambda = BuildFuncExpression(tableType, keyProperty);
// MethodAccessException
mi.Invoke(this, new object[] { lambda });
}
private System.Linq.Expressions.LambdaExpression BuildFuncExpression(Type paramType, PropertyInfo keyProperty)
{
ParameterExpression parameter = System.Linq.Expressions.Expression.Parameter(paramType, "x");
MemberExpression member = System.Linq.Expressions.Expression.Property(parameter, keyProperty);
return System.Linq.Expressions.Expression.Lambda(member, parameter);
}
}
};
我得到了 MethodAccessException。我知道这是一个安全异常,但我可以从那个地方正常调用该方法,所以我也应该可以通过反射调用它。
可能有什么问题?谢谢!