这直接针对该功能进行编码。
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
}
}
}
我意识到这些不是真实世界的数字,但它确实为使用反射而不是异常提供了一个非常有说服力的论据。