【问题标题】:NuGet package addressing multiple Standard frameworks - problem with nullables解决多个标准框架的 NuGet 包 - 可空值问题
【发布时间】:2020-06-22 19:07:26
【问题描述】:

我们有一系列 .Net Core 3.1 应用程序。我们将通用代码抽象为 .NetStandard 2.1 NuGet 包,并在我们的私有 NuGet 服务器上提供这些代码。

这就是这些 NuGet 包的成功,我们被要求将它们提供给我们用 .Net Framework 4.8 编写的其他应用程序。

我们遵循了 Microsoft (Support multiple .NET Framework versions in your project file) 提供的建议,除了我们的一个包之外,这对所有包都有效......

那么 - 这个有什么不同?

这个包使用空值。我可以让项目编译得很好,但是抛出异常的是测试项目(.NetCore 3.1)。我将首先检查我们在标准项目中所做的代码更改,然后查看测试项目 - 希望有人会发现我们出错的地方。

.Net 标准项目

.csproj 文件

改变了

<TargetFramework>netstandard2.1</TargetFramework>

<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>

还将&lt;Nullable&gt;enable&lt;/Nullable&gt; 移至其自己的部分

  <PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard2_1' ">
    <Nullable>enable</Nullable>
  </PropertyGroup>

班级

然后我们有一个类文件。我不会费心展示基类,但它遵循类似的模式:

public class MyClass<T> : MyBaseClass
        where T : struct
{
    public MyClass()
        : this(default)
    {
    }

#if netstandard2_1
    public MyClass(T? item)
        : base(true, 0, null)
    {
        this.Item = item;
    }
#else
    public MyClass(T item)
        : base(true, 0, null)
    {
        this.Item = item;
    }
#endif

#if netstandard2_1
    public T? Item { get; set; }
#else
    public T Item { get; set; }
#endif
}

这会编译并在 bin/release 文件夹(或 bin/debug)中看到两个文件夹,一个用于 netstandard2.1,另一个用于 netstandard2.0,每个文件夹中都有预期的 DLL。

但是,使用 ILSPY 检查两个 DLL 中的此类会显示它们是相同的……而不是一个问号。不确定这是 ILSPY 的神器还是真实的......

测试项目

所以测试项目有一个对标准项目的项目引用(所以,它不是对 NuGet 包的引用)。

在我进行的一项测试中:

Guid? g = null;
var actual = new ItemValueOperationResponse<Guid>(g);

这会导致以下错误:

CS1503 参数 1:无法从“System.Guid?”转换到'System.Guid'

但是,这个测试项目是.Net Core 3.1,所以它应该使用Standard2.1代码。

我尝试交换 *.csproj 中的序列,使其读取为&lt;TargetFrameworks&gt;netstandard2.1;netstandard2.0&lt;/TargetFrameworks&gt;,但无济于事。

也尝试使用大写:#if NETSTANDARD2_1

【问题讨论】:

  • 在您的属性组中,您已将点替换为下划线。此值应与&lt;TargetFrameworks&gt; 中的项目完全相同,因此应为'$(TargetFramework)' == 'netstandard2.1'
  • 你的代码应该使用#if NETSTANDARD2_1(全部大写,带下划线)。
  • 正如@madreflection 所指出的,您需要全部使用大写。在 Visual Studio 中,您可以使用代码窗口左上角的下拉菜单来更改代码版本。当你这样做时,你应该看到你的代码部分在被消除时变成灰色。
  • 另外看看你的测试项目引用,它是否显示了你的测试嵌套在框架版本下面的项目?
  • Guid 是一个结构,而不是一个类,所以Guid?Guid 的类型不兼容。 nullable 检查仅适用于引用类型,不适用于值传递类型。

标签: c# .net-core nuget nullable .net-standard


【解决方案1】:

最终在我们的测试项目中有区域。

【讨论】:

    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2016-07-26
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多