在Windows 10 UWP (15063(中,我需要在调用程序集时迭代类型,以发现装饰有特定自定义属性的类型。 我找不到旧的System.Reflection.Assembly.Current.GetCallingAssembly((方法。 这是我想出的替代方案(未经测试的原型(:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
namespace UWPContainerUtility
{
public static class Helpers
{
public static Assembly GetCallingAssembly()
{
var thisAssembly = typeof(Helpers).GetTypeInfo().Assembly;
StackFrame[] frames = GetStackTraceFrames();
var result = frames.Select(GetFrameAssembly)
.FirstOrDefault(NotCurrentAssembly);
return result;
StackFrame[] GetStackTraceFrames()
{
StackTrace trace = null;
try
{
throw new Exception();
}
catch (Exception stacktraceHelper)
{
trace = new StackTrace(stacktraceHelper, true);
}
return trace.GetFrames();
}
Assembly GetFrameAssembly(StackFrame f)
{
return f.GetMethod().DeclaringType.GetTypeInfo().Assembly;
}
bool NotCurrentAssembly(Assembly a)
{
return !ReferenceEquals(thisAssembly, a);
}
}
}
}
除了抛出虚假异常之外,目前真的没有其他方法可以做到这一点吗?真正的方法是什么?
提前感谢!
*为清楚起见,编辑了示例代码
我认为这是最好的方法:
IEnumerable<Assembly> GetCallingAssemblies()
{
var s = new StackTrace();
return s.GetFrames()
.Select(x => x.GetMethod().DeclaringType.GetTypeInfo().Assembly)
.Where(x => !Equals(x, GetType().GetTypeInfo().Assembly))
.Where(x => !x.FullName.StartsWith("Microsoft."))
.Where(x => !x.FullName.StartsWith("System."));
}
Assembly GetCallingAssembly()
{
return GetCallingAssemblies().First();
}
请注意,这不是每个项目的即插即用解决方案。您将需要对其进行测试和调整,因为Microsoft。和系统。可能不适合你的方案。您可能有更多或更少的程序集要从列表中筛选出来。在过滤掉当前之后选择第一个似乎是获取调用程序集的最明显方法,但根据堆栈的构建方式,这也可能需要进行调整。
关键是,有一种方法,这会让你开始。
祝你好运。