在便携式项目上是否有 AppDomain.GetAssemblies 的替代方案?

Is there an alternative to AppDomain.GetAssemblies on portable project?

我正在尝试获取程序集列表。但是我在 portable UWP 项目中遇到异常。

以下代码适用于

.netframework

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

Xamarin portable

var currentdomain = typeof(string).GetTypeInfo().Assembly.GetType("System.AppDomain").GetRuntimeProperty("CurrentDomain").GetMethod.Invoke(null, new object[] { });
var getassemblies = currentdomain.GetType().GetRuntimeMethod("GetAssemblies", new Type[] { });
var assemblies = getassemblies.Invoke(currentdomain, new object[] { }) as Assembly[];

但是上面的代码在 UWP portable 中不起作用。 (我认为便携式也在 UWP 中工作)

我在点击第一行时遇到以下问题

'typeof(string).GetTypeInfo().Assembly.GetType("System.AppDomain").GetRuntimeProperty("CurrentDomain").GetMethod.Invoke(null, new object[] { })' threw an exception of type 'System.InvalidOperationException'
Data: {System.Collections.ListDictionaryInternal} HResult: -2146233079 HelpLink: null InnerException: null Message: "The API 'System.AppDomain.get_CurrentDomain()' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information." Source: "mscorlib" StackTrace: " at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\r\n at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)"

如果我使用下面的代码

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Assembly[] assembly = ((dynamic)Thread.GetDomain()).GetAssemblies() as Assembly[];
var loadedAssemblies = ((dynamic)Thread.GetDomain()).GetAssemblies() as Assembly[];

然后我得到以下错误。

The name 'AppDomain' does not exist in the current context

The name 'Thread' does not exist in the current context

The name 'Thread' does not exist in the current context

我检查了 Is there an alternative to AppDomain.GetAssemblies on portable library?,但这对解决我的问题没有帮助。

首先,.NET Standard 库是便携式 Class 库 (PCL) 的替代品。参见.NET Standard 2.0 Support in Xamarin.Forms。您可以使用以下代码获取UWP应用程序包中的所有程序集,

private async Task<List<Assembly>> GetAssemblyListAsync()
{
    var PackageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

    List<Assembly> assemblies = new List<Assembly>();
    foreach (StorageFile file in await PackageFolder.GetFilesAsync())
    {
        if (file.FileType == ".dll" || file.FileType == ".exe")
        {
            AssemblyName name = new AssemblyName() { Name = file.Name };
            Assembly asm = Assembly.Load(name);
            assemblies.Add(asm);
        }
    }
    return assemblies;
}

但是,从 .Net 标准 2.0 开始,您可以直接在 UWP 应用程序中使用 AppDomain.GetAssemblies 来获取程序集。

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

您需要下载 Visual Studio 2017 15.4 或更高版本并设置您的应用目标版本和最低版本 Windows 10 Fall Creators Update (16299)。此外,您还可以创建一个 .Net Standard 2.0 class 库来使用 AppDomain.GetAssemblies.

Windows.UI.Xaml.Application.Current.GetType().GetTypeInfo().Assembly;