前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >验证兼容的框架

验证兼容的框架

作者头像
用户4268038
发布2022-01-09 12:11:43
发布2022-01-09 12:11:43
5940
举报
文章被收录于专栏:stcnbstcnb

包含兼容框架的包需要确保针对某个框架编译的代码可以针对另一个框架运行。 兼容框架对的示例包括:

.NET Standard 2.0 和 .NET 6

.NET 5 和 .NET 6

在这两种情况下,使用者均可针对 .NET Standard 2.0 或 NET 5 构建框架并在 .NET 6 上运行。 如果二进制文件在这些框架上不兼容,使用者最终可能会遇到编译时或运行时错误。

包验证将在打包时捕获这些错误。 示例场景如下:

假设你正在编写一个操作字符串的游戏。 需要同时支持 .NET Framework 和 .NET (.NET Core) 使用者。 最初,项目面向 .NET Standard 2.0,但现在你想利用 .NET 6 中的 Span<T> 以避免不必要的字符串分配。 为此,需要同时以 .NET Standard 2.0 和 .NET 6 为目标。

你已经编写了以下代码:

#if NET6_0_OR_GREATER

public void DoStringManipulation(ReadOnlySpan<char> input)

{

// use spans to do string operations.

}

#else

public void DoStringManipulation(string input)

{

// Do some string operations.

}

#endif

然后,你尝试(使用 dotnet pack 或 Visual Studio)打包项目,但失败了并显示以下错误:

D:\demo>dotnet pack

Microsoft (R) Build Engine version 17.0.0-preview-21460-01+8f208e609 for .NET

Copyright (C) Microsoft Corporation. All rights reserved.

Determining projects to restore...

All projects are up-to-date for restore.

You are using a preview version of .NET. See: https://aka.ms/dotnet-core-preview

You are using a preview version of .NET. See: https://aka.ms/dotnet-core-preview

PackageValidationThrough -> D:\demo\bin\Debug\netstandard2.0\PackageValidationThrough.dll

PackageValidationThrough -> D:\demo\bin\Debug\net6.0\PackageValidationThrough.dll

Successfully created package 'D:\demo\bin\Debug\PackageValidationThrough.1.0.0.nupkg'.

C:\Program Files\dotnet\sdk\6.0.100-rc.1.21463.6\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Compatibility.Common.targets(32,5): error CP0002: Member 'A.B.DoStringManipulation(string)' exists on lib/netstandard2.0/PackageValidationThrough.dll but not on lib/net6.0/PackageValidationThrough.dll [D:\demo\PackageValidationThrough.csproj]

你意识到,与其为 .NET 6 排除 DoStringManipulation(string),不如为 .NET 6 提供一个额外的 DoStringManipulation(ReadOnlySpan<char>) 方法:

#if NET6_0_OR_GREATER

public void DoStringManipulation(ReadOnlySpan<char> input)

{

// use spans to do string operations.

}

#endif

public void DoStringManipulation(string input)

{

// Do some string operations.

}

你尝试再次打包该项目,然后就成功了。

通过在项目文件中设置 EnableStrictModeForCompatibleFrameworksInPackage 属性为此验证程序启用“严格模式”。 启用严格模式后,将更改一些规则,并在存在差异时执行一些其他规则。 如果希望所比较的双方在领域和标识方面完全相同,这十分有用。

本文系外文翻译,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系外文翻译前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档