微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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很清楚已被锁定以防止此类访问.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐