在.NET Core中引用时,从程序集文件加载的类型不等于相同的类型 [英] Types loaded from an assembly file are not equal to the same type when referenced in .NET Core

查看:314
本文介绍了在.NET Core中引用时,从程序集文件加载的类型不等于相同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我选择一个 Type ,查询其程序集位置,然后从相同的地址加载该程序集,并从已加载的程序集中找到相同的类型。结果类型不等于原始类型。



这里是测试用例:

  [TestMethod] 
public void TestTypeLoadingWithFilePath()
{
var originalType = typeof(SomeClass);
var assemblyAddress = originalType.Assembly.Location;

varloadedAssembly = Assembly.LoadFile(assemblyAddress);
Assert.IsNotNull(loadedAssembly);

varloadedType = loadedAssembly.GetType(originalType.FullName);
Assert.IsNotNull(loadedType);

Assert.AreEqual(originalType,loadedType);
}

最后一个断言测试失败。



这仅在Windows的.NET Core上发生。 (我正在针对最新版本2.1.4进行测试)。但这不是.NET Framework的情况。



我的问题是:




  • 这是设计使然还是错误?

  • 如果是设计使然,为什么?

  • 再次,如果是设计使然,不是这意味着.NET Standard的两种实现之间的行为是否不同? (.NET Core与.NET Framework)


解决方案

这是正常现象。使用 Assembly.LoadFile 将加载程序集并为其创建新的实例。要解决此问题,只需使用 Assembly.LoadFrom 即可。如果请求的程序集已经加载,它将首先在当前上下文中查找,如果已加载,则将其视为当前上下文。



编辑:我不知道它是否是预期的,但是该方法在.NetFramework和.NetCore中都可以使用。 / p>

I take a Type, query its assembly location, and then load the assembly from the same address, and find the same type from the loaded assembly. The resulting type is not equal to the original type.

Here's the test case:

[TestMethod]
public void TestTypeLoadingWithFilePath()
{
    var originalType = typeof(SomeClass);
    var assemblyAddress = originalType.Assembly.Location;

    var loadedAssembly = Assembly.LoadFile(assemblyAddress);
    Assert.IsNotNull(loadedAssembly);

    var loadedType = loadedAssembly.GetType(originalType.FullName);
    Assert.IsNotNull(loadedType);

    Assert.AreEqual(originalType, loadedType);
}

The test fails on the last assertion.

This only happens on .NET Core on Windows. (I'm testing against latest version, 2.1.4). But this was not the case with .NET Framework.

My questions are:

  • Is this by design, or a bug?
  • If it's by design, why?
  • Again, if it's by design, doesn't this mean different behavior between two implementations of .NET Standard? (.NET Core vs. .NET Framework)

解决方案

This is a normal behavior. Using Assembly.LoadFile will load the assembly and create a new "instance" of it. To fix this, simply use Assembly.LoadFrom instead. This will first look in the current context if the requested assembly is already loaded, and take this one if it is. Comparing types like you're doing will then work.

Edit: I don't know if it's intended, but this method works in both .NetFramework and .NetCore.

这篇关于在.NET Core中引用时,从程序集文件加载的类型不等于相同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆