开发者

Call protected generic method via .NET reflection within derived class

recently I was trying to do something like this in WP7 app

I have class

abstract class A {
//this method has an implementation
protected void DoSomething<T, TKey>(Func<T, TKey> func) { //impl here }
};

and I want to invoke that protected method via reflection in derived class:

    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() });

            LambdaExp开发者_运维技巧ression 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);
        }


}
    };

and I'm getting MethodAccessException. I understand this is a security exception but I'm able to call the method normally from that place, so I should be able to call it via reflection as well.

What might be wrong? Thanks!


From http://msdn.microsoft.com/en-us/library/system.methodaccessexception.aspx

This exception is thrown in situations such as the following:

  • A private, protected, or internal method that would not be accessible from normal compiled code is accessed from partially trusted code by using reflection.

  • A security-critical method is accessed from transparent code.

  • The access level of a method in a class library has changed, and one or more assemblies that reference the library have not been recompiled.

Within WP7, I think the problem is most likely to be that this reflection code attempts to access private (NonPublic) methods - and WP7 has been very clear that it is locked down to prevent this type of access.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜