0

DynamicMethodC#中创建不需要或不相关绕过可见性的 a 时,为构造函数的skipVisibility参数指定的最佳值是什么DynamicMethod?是否存在性能损失,即与运行时安全需求相关联,用于指定trueskipVisibility 如果是这样,惩罚是否会在每次调用时发生,或者在第一次访问之前在 JIT 时间仅发生一次?

MSDN 文档:DynamicMethod

4

1 回答 1

0

我在.NET参考源中找到了一些相关代码DynamicMethod。如下所示,指定skipVisibility强制要求ReflectionPermission. (代码还有另一种情况,无论skipVisibility参数如何,都需要此权限)。

[SecurityCritical]
private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility)
{
    if (owner == null)
        throw new ArgumentNullException("owner");

    RuntimeType underlyingSystemType = owner as RuntimeType;
    if (underlyingSystemType == null)
        underlyingSystemType = owner.UnderlyingSystemType as RuntimeType;

    if (underlyingSystemType == null)
        throw new ArgumentNullException("owner", Environment.GetResourceString("Argument_MustBeRuntimeType"));

    RuntimeType callerType = RuntimeMethodHandle.GetCallerType(ref stackMark);
    if (skipVisibility)
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
    else if (callerType != underlyingSystemType)
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();

    this.m_creatorAssembly = callerType.GetRuntimeAssembly();
    if (underlyingSystemType.Assembly != this.m_creatorAssembly)
        CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, owner.Assembly.PermissionSet);
}

因此,答案是在为指定true时可能会有性能损失skipVisibility。但是,根据您使用的各种其他参数类型new DynamicMethod(...)以及您发出的 IL,您DynamicMethod可能实际需要 ReflectionPermission,并且您将无法指定false。在这种情况下给出的错误是:

System.TypeAccessException尝试通过安全透明方法“DynamicClass.foo(MyType,int)”访问安全关键类型“MyType”失败。

于 2018-01-13T22:41:41.247 回答