c# - 在 Windows 10 通用 Windows 库中引用 BindingFlags 类型时无法加载程序集

标签 c# .net portable-class-library visual-studio-2015

运行单元测试时,在我的可移植运行时库 DLL 中调用任何引用“System.Reflection.TypeExtensions”的方法都会生成 FileNotFound 异常,搜索“System.Reflection.TypeExtensions”。在 Windows 10 通用应用程序中执行相同的代码时,不会发生该错误。

该项目是一个 C# 可移植运行时库,配置为支持 .net Framework 4.6 和 Windows Universal 10.0。测试项目配置为使用 .net Framework 4.6。

每当我尝试调用使用 System.Reflection.BindingFlags 类型的方法时,我都会收到以下异常。异常发生在调用开始时(大概是在对函数进行 jit 时)。

Test method Sfx.Test.SignalExpressionTest.TestAddExpressions threw exception: 
System.IO.FileNotFoundException: Could not load file or assembly 'System.Reflection.TypeExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.=== Pre-bind state information ===
LOG: DisplayName = System.Reflection.TypeExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)

最佳答案

添加这些包是正确的做法。这就是您看到此行为的原因:

  1. BindingFlags 目前 [1] 在 System.Reflection.TypeExtensions 中公开。
  2. 当您编译 .NET Core 类库时,编译器将类型引用记录为 System.Reflection.TypeExtensions!System.Reflection.BindingFlags
  3. 当您使用 .NET Framework 应用程序中的类库时,您需要添加对 System.Reflection.TypeExtensions 的引用,否则编译器无法解析类型。对于必须部署所有代码才能运行的单元测试项目也是如此。
  4. 在运行时,CLR 将解析类型,找到指向 mscorlib!System.Reflection.BindingFlags 的类型并愉快地运行您的代码。

作为一般经验法则:.NET Core 旨在以应用程序本地方式部署框架,换句话说,当您的应用程序部署到文件夹时,也需要关闭所有依赖项来部署.虽然单元测试项目在概念上是类库,但同样适用,因为它们像应用程序一样执行。

当然,我们不希望人们手动调整引用并寻找依赖项。您目前看到的是预发布位,其中并非我们工具体验中的所有部分都做正确的事情。

我的两个问题:

  1. 您使用哪个单元测试框架?我假设它是 MSTest (Microsoft.VisualStudio.TestTools.UnitTesting),而不是 xUnit 或 NUnit?

  2. 您使用的是哪个运行者?我假设它是内置的 Visual Studio 测试资源管理器(而不是 ReSharper 或 TestDriven.NET)?


[1] 我说目前是因为根据客户反馈我们decided将其与采用 BindingFlags 的 API 一起移回 System.Reflection

关于c# - 在 Windows 10 通用 Windows 库中引用 BindingFlags 类型时无法加载程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35246007/

相关文章:

c# - GUI 设计 : Hide/Show controls at run time

c# - WinRT 中的后台任务

c# - 数组内存分配说明

c# - C# .NET 中的最佳数据集合

c# - 在一个查询中获取基类和继承类的文档

.net - IDataErrorInfo.Error 应该检查每个属性吗?

c# - 克隆类定义 (PCL)

c# - 无法在 Win 8 和 Win Phone 8 的可移植类库中使用 await

c# - 是否可以将 Windows 服务添加到现有项目中?

c# - 什么是托管模块(与程序集相比)?