这是在 Windows 10 UWP 中获取调用程序集的最佳方式吗?

The*_*ker 5 c# reflection windows-runtime uwp

在 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);
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

除了抛出虚假异常之外,目前是否真的没有其他方法可以做到这一点?真正的方法是什么?

提前致谢!

*为清楚起见编辑了示例代码

Jer*_*xon 3

我认为这是最好的方法:

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();
}
Run Code Online (Sandbox Code Playgroud)

请注意,这并不是适用于每个项目的即插即用解决方案。您将需要测试和调整它,因为 Microsoft. 和系统。可能不适合您的场景。您可能需要从列表中过滤出更多或更少的程序集。在过滤掉当前程序集后选择第一个似乎是获取调用程序集的最明显方法,但根据堆栈的构建方式,这也可能需要调整。

关键是,有一种方法可以帮助您入门。

祝你好运。