编程语言
首页 > 编程语言> > c#-通过.NET反射在派生类中调用受保护的泛型方法

c#-通过.NET反射在派生类中调用受保护的泛型方法

作者:互联网

最近我正在尝试在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.我知道这是一个安全异常,但是我可以从那个地方正常调用该方法,因此我也应该能够通过反射来调用它.

可能是什么问题?谢谢!

解决方法:

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.

在WP7中,我认为问题很可能是此反射代码尝试访问私有(NonPublic)方法-WP7很清楚已被锁定以防止此类访问.

标签:code-access-security,generics,windows-phone-7,c,silverlight
来源: https://codeday.me/bug/20191102/1994492.html