"Could not load file or assembly" net462 应用程序引用 netstandard1.5 库时出错。但为什么?

"Could not load file or assembly" error when net462 app references a netstandard1.5 library. But why?

我想弄清楚我在这个示例项目中可能做错了什么。当我的 net462 应用程序引用 netstandard1.5 库时出现错误。该应用程序依赖于 "System.Collections.Immutable": "1.3.0",根据 Nuget,它以 NetStandard 1.0 为目标。该库依赖于 "NETStandard.Library": "1.6.0"

我是否设置了这些项目中的任何一个错误?如果对此有任何见解,我将不胜感激...

这是他们的 project.json :

应用程序:

{
  "buildOptions": {
    "emitEntryPoint": true
  },
  "dependencies": {
    "SomeLibrary": "1.0.0-*"
  },
  "frameworks": {
    "net462": {
      "dependencies": {
        "System.Collections.Immutable": "1.3.0" 
      }
    }
  },
  "version": "1.0.0-*"
}

图书馆

{
  "buildOptions": {
    "allowUnsafe": true
  },
  "dependencies": {
  },
  "frameworks": {
    "netstandard1.5": {
      "dependencies": {
        "NETStandard.Library": "1.6.0"
      }
    }
  },
  "version": "1.0.0-*"
}

图书馆只有这个界面:

using System.Collections.Generic;

namespace SomeLibrary
{
    public interface SomeInterface
    {
        int GetValue(KeyValuePair<string, int> somePair);
    }
}

应用程序实现了这个接口并调用了具体的class:

public class Program
{
    public static void Main(string[] args)
    {
        var concreteObject = new ConcreteImplementation();
        var answer = concreteObject.GetValue(new KeyValuePair<string, int>("key", 33));
        Console.WriteLine(answer);
    }
}


class ConcreteImplementation : SomeInterface
{
    public int GetValue(KeyValuePair<string, int> somePair)
    {
        return somePair.Value;
    }
}

如果我尝试 运行 应用程序,这是我得到的错误:

{"Could not load file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.":"System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}

堆栈:at ErrorExample.Consumer..ctor() at ErrorExample.Program.Main(String[] args) in ..\ErrorExample\src\ErrorExample\Program.cs:line 11

我在这里错过了什么? 谢谢!

我不太清楚为什么会这样,但是使用 netstandard1.4 作为图书馆项目的 TFM 可以解决您的问题。换句话说,project.json 你的图书馆应该是这样的:

{
  "buildOptions": {
    "allowUnsafe": true
  },
  "dependencies": {
  },
  "frameworks": {
    "netstandard1.4": { // <-- replace "netstandard1.5" with "netstandard1.4" or lower
      "dependencies": {
        "NETStandard.Library": "1.6.0"
      }
    }
  },
  "version": "1.0.0-*"
}

并且作为当前的一般经验法则:避免使用 netstandard1.5netstandard1.6:使用 netstandard1.4 并根据您的要求降低直到你被明确强迫。等待 netstandard2.0 的发布。您可以在 MSDN blog artible about .NET Standard. And here's a FAQ.

中阅读有关它的详细信息