【问题标题】:Assembly.LoadFrom works differently in .NET Core and .NET FrameworkAssembly.LoadFrom 在 .NET Core 和 .NET Framework 中的工作方式不同
【发布时间】:2019-01-12 03:07:48
【问题描述】:

我有两个.csproj 项目,源代码完全相同:

using Newtonsoft.Json.Linq;
using System;
using System.Reflection;
class Program
{
    static void Main(string[] args)
    {
        Assembly jsonAssembly = Assembly.LoadFrom(@"C:\path\to\Newtonsoft.Json.dll");
        Type reflectionType = jsonAssembly.GetType("Newtonsoft.Json.Linq.JObject");

        Console.Write("Types match: " + (reflectionType == typeof(JObject)));
        Console.Write("Typenames match: " + (reflectionType.FullName == typeof(JObject).FullName));

        JObject cast = (JObject)Activator.CreateInstance(reflectionType);
        Console.Write("Success!");
    }
}

.csproj 两个文件都对 Newtonsoft.Json 有相同的引用:

<Reference Include="Newtonsoft.Json">
  <HintPath>C:\path\to\Newtonsoft.Json.dll</HintPath>
</Reference>

这两个项目的唯一区别是我使用 .NET Core 2.0 创建了第一个项目,而使用 .NET Framework 4.6.1 创建了第二个项目。

框架:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{A6D2C332-B60D-41F1-9983-DE10065973A1}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <RootNamespace>ConsoleApp1</RootNamespace>
    <AssemblyName>ConsoleApp1</AssemblyName>
    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Newtonsoft.Json">
      <HintPath>C:\path\to\Newtonsoft.Json.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

核心:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
  </PropertyGroup>

  <ItemGroup>
    <Reference Include="Newtonsoft.Json">
      <HintPath>C:\path\to\Newtonsoft.Json.dll</HintPath>
    </Reference>
  </ItemGroup>

</Project>

当我使用 .NET Core 运行上述代码时,我得到以下响应:

Types match: True
Typenames match: True
Success!

当我使用 .NET Framework 运行上述代码时,我得到以下响应:

Types match: False
Typenames match: True

Unhandled Exception: System.InvalidCastException: [A]Newtonsoft.Json.Linq.JObject cannot be cast to [B]Newtonsoft.Json.Linq.JObject

为什么 .NET Framework 和 .NET Core 在通过反射加载程序集时工作方式不同?

【问题讨论】:

  • 您引用的是哪个版本的 Newtonsoft.Json.dll?我已经在 .NET Framework 4.6.1 和 .NET Core 2.0 中编译了您的代码。在这两种情况下,我在类型匹配中都得到了“真”。我是12.0.1版本。
  • Newtonsoft.Json 9.0.1。然而,包裹在过去并不重要。 (它适用于其他包)我将添加我的 csproj 文件。
  • @HansPassant 这与 Newtonsoft.JSON 无关。我可以使用任何程序集复制它。

标签: c# .net .net-core


【解决方案1】:

问题可能是,在 .NET Framework 中,您使用 2 个不同的程序集(磁盘上的 2 个不同文件)。尝试在调试模式下运行 .NET Framework 项目并查看这些类型的来源或添加这些行。

Console.Write("Reflection type module: " + (reflectionType.Module.FullyQualifiedName));
Console.Write("Static type module: " + (typeof(JObject).Module.FullyQualifiedName));

受沃尔特布兰森回答的启发,我做了一些研究,发现了一些 Load 方法的行为方式。

    /* Loads closest assembly given by FullName loaded by default, in this case it is from the same location as executable */
    Assembly jsonAssembly1 = Assembly.Load(@"Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed");

    /* Loads assembly exaclty from the file specified by path */
    Assembly jsonAssembly2 = Assembly.LoadFile($@"{pathToAssembly}\Newtonsoft.Json.dll");

    /* In NET.Framework loads same assembly as LoadFrom, but in .NET Core loads same assembly as Load */
    Assembly jsonAssembly3 = Assembly.LoadFrom($@"{pathToAssembly}\Newtonsoft.Json.dll");

【讨论】:

  • 你是对的:.NETFramework 使用了 2 个不同的程序集(不同的路径)。不过,我仍然不确定为什么会这样。
  • 当我为 .NET Core 项目运行此程序时,我看到两者都来自同一个程序集,并且来自可执行文件所在的程序集,它忽略了我使用 Assembly.LoadFrom(". ..\Newtonsoft.Json.dll")
  • 我发现了一个可能与此问题有关的问题github.com/dotnet/corefx/issues/21982
【解决方案2】:

我相信这是因为 .NET 的引用比较失败。当您查看对象时,.NET 中有不同的句柄。当您查看核心中的对象时,它们都有相同的句柄。

我认为这是因为您正在从文件加载程序集。尝试按其完全限定名称加载程序集。

Assembly jsonAssembly = Assebmly.Load("NewtonSoft.Json,Version=12.0.0.0,Culture=neutral,PublicKeyToken=30adfe6b2a6aeed")

【讨论】:

    【解决方案3】:

    .NET Framework 之一将您引用的 .dll 复制到其可执行目录。所以加载的.dll其实是不一样的。

    尝试将.NET Framework项目中的"C:\path\to\Newtonsoft.Json.dll"路径改成"Newtonsoft.Json.dll",结果和.NET Core一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多