3

在 .NET 4 中,代码访问安全 (CAS) 已被弃用。每当您调用隐式使用它的方法时,它都会失败并显示NotSupportedException,这可以通过配置开关解决,使其回退到旧行为。

我们有一个在 .NET 3.5 和 .NET 4 中都使用的通用库,因此我们需要能够判断是否应该使用 CAS 方法。

例如,在 .NET 3.5 中,我应该调用:

Assembly.Load(string, Evidence);

而在 .NET 4 中我想调用

Assembly.Load(string);

调用Load(string, Evidence)抛出一个NotSupportedException.

当然这可行,但我想知道是否有更好的方法:

try
{
    asm = Assembly.Load(someString, someEvidence);
}
catch(NotSupportedException)
{
    asm = Assembly.Load(someString);
}
4

3 回答 3

2

嗨,使用Environment.Version.MajorEnvironment.Version.Minor应该可以解决问题。

Version v = Environment.Version;
if (Environment.Version.Major <= 3)
{
    //DO 3.5 here
}
else if (Environment.Version.Major >= 4)
{
     //DO 4 here
}

希望这可以帮助。

编辑:更改条件以假设相同的 CAS 将在 .NET 的未来版本中实现。

于 2010-03-26T17:15:19.107 回答
1

这直接针对该功能进行编码。

    public static Assembly LoadAssembly(string assembly, Evidence evidence)
    {
        Assembly asm;
        MethodInfo load = 
            typeof(Assembly).GetMethod("Load", 
                                        new Type[] {typeof(string), typeof(Evidence)});

        if (Attribute.IsDefined(load, typeof(ObsoleteAttribute)))
        {
            asm = Assembly.Load(assembly);
        }
        else
        {
            asm = Assembly.Load(assembly, evidence);
        }
        return asm;
    }

此代码假定以下 using 语句。

using System;
using System.Reflection;
using System.Security.Policy;

如果这将被频繁调用,您可以避免反射性能受到这样的影响。

private static bool? _isEvidenceObsolete = null;
public static Assembly AssemblyLoader(string assembly, Evidence evidence)
{
    Assembly asm;
    if (!_isEvidenceObsolete.HasValue)
    {
        MethodInfo load =
           typeof(Assembly).GetMethod("Load",
                                       new Type[] { typeof(string), typeof(Evidence) });
        _isEvidenceObsolete = Attribute.IsDefined(load, typeof(ObsoleteAttribute));
    }

    if (_isEvidenceObsolete.Value)
    {
        asm = Assembly.Load(assembly);
    }
    else
    {
        asm = Assembly.Load(assembly, evidence);
    }
    return asm;
}

编辑:我必须自己看看性能统计数据是什么,这就是我得到的。

以毫秒为单位的经过时间:

Catch Exception: 45331
Reflection: 58
Static Reflection: 1

这是我用来进行基准测试的代码:

public static void BenchmarkLoaders()
{
    Stopwatch timer = new Stopwatch();

    // Benchmark catching Exceptions
    timer.Start();
    for (int i = 0; i < 10000; i++)
    {
        NotSupported notSupported = new NotSupported();
        try
        {
            notSupported.ThrowException("Obsoleted Method Call");
        }
        catch (NotSupportedException nse)
        {
            //Do something
        }
    }
    timer.Stop();
    Console.WriteLine("Catch Exception: {0}", timer.ElapsedMilliseconds);
    timer.Reset();

    // Benchmark Reflection
    timer.Start();
    for (int i = 0; i < 10000; i++)
    {
        NotSupported notSupported = new NotSupported();

        notSupported.ReflectAssembly();
    }
    timer.Stop();
    Console.WriteLine("Reflection: {0}", timer.ElapsedMilliseconds);
    timer.Reset();


    // Benchmark Static Reflection
    timer.Start();
    for (int i = 0; i < 10000; i++)
    {
        NotSupported.ReflectAssemblyStatic();
    }
    timer.Stop();
    Console.WriteLine("Static Reflection: {0}", timer.ElapsedMilliseconds);
    timer.Reset();

}

这是NotSupported课堂。

public class NotSupported
{
    public void ThrowException(string message)
    {
        throw new NotSupportedException(message);
    }

    public void ReflectAssembly()
    {
        MethodInfo load = 
            typeof(Assembly).GetMethod("Load", 
                                        new Type[] { typeof(string), typeof(Evidence) });

        if (Attribute.IsDefined(load, typeof(ObsoleteAttribute)))
        {
            // Do something
        }
    }

    private static bool? _isEvidenceObsolete = null;
    public static void ReflectAssemblyStatic()
    {
        Assembly asm;
        if (!_isEvidenceObsolete.HasValue)
        {
            MethodInfo load =
               typeof(Assembly).GetMethod("Load",
                                           new Type[] { typeof(string), typeof(Evidence) });
            _isEvidenceObsolete = Attribute.IsDefined(load, typeof(ObsoleteAttribute));
        }

        if (_isEvidenceObsolete.Value)
        {
            //Do Stuff
        }
    }
}

我意识到这些不是真实世界的数字,但它确实为使用反射而不是异常提供了一个非常有说服力的论据。

于 2010-03-31T15:10:16.473 回答
0

System.Security.HostSecurityManager.DomainPolicy 属性的 getter 是一种公共的轻量级方法,如果不应用旧 CAS 策略开关,它将在 .NET 4.0 中快速失败。您可能需要考虑设置一个帮助程序类,以允许您避免多次产生潜在异常的成本。 例如

internal static class CasPolicyHelper
{
    private static bool? _isCasPolicyEnabled;

    internal static bool IsCasPolicyEnabled
    {
        get
        {
            if (_isCasPolicyEnabled == null)
            {
                HostSecurityManager hostSecurityManager = new HostSecurityManager();
                try
                {
                    PolicyLevel level = hostSecurityManager.DomainPolicy;
                    _isCasPolicyEnabled = true;
                }
                catch (NotSupportedException)
                {
                    _isCasPolicyEnabled = false;
                }
            }

            return _isCasPolicyEnabled.Value;
        }
    }
}
于 2010-03-29T13:49:20.713 回答