首页 > 解决方案 > 代码在 .Net 5 中有效,但在 .Net 6 中无效

问题描述

我已经通过 Visual Studio 反馈工具报告了这个可能的错误,但是我有以下示例代码在 .Net 5 中运行,但在 .Net 6 中无法正常工作,我觉得这要么是一个错误,要么是我遗漏了一些东西版本之间发生了变化。我有下面的示例代码以及使用两种方法的 Visual Studio html 可视化器的 html 输出。有人对这个问题有任何可能的意见吗?

更新:由于@GSerg的有用建议,通过不同的测试,我发现这个错误只发生在.Net 6中,当您在字符串插值或字符串构建器中使用html标签时,它会在插入变量之前切断文本并插入它在第二行。我附上了一个新的屏幕截图,显示了使用 Visual Studio 可视化工具的这种行为。

var subect = "Subect Example";
var test = $"<p><strong><span style=\"font-size: 20px;\">{subject}</span></strong></p><p><span style=\"color: rgb(34, 34, 34); font-family: Arial, Helvetica, sans-serif; " +
           $"font-size: small; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; " +
           $"text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; " +
           $"text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;\">The following information is in beta testing and isn't meant for a live portfolio. " +
           $"Use this information for paper trading only until further notice.</span></p>";

.Net 5 HTML 输出: 在此处输入图像描述

.Net 6 HTML 输出: 在此处输入图像描述

.Net 6 文本输出: 在此处输入图像描述

标签: c#.net-5stringbuilder.net-6.0

解决方案


这似乎是 Visual Studio 2022 中的一个错误,它仍处于预览阶段,因此并不意外。虽然此错误未修复,但您可以使用 dotnet cli 构建作为解决方法。

以下代码重现了该错误

string two= "2";
string test = $"1 {two} 3" 
    + $" 4" 
    + $" 5";
Console.WriteLine(test);

使用 Visual Studio 2022 预览版 3.1 将此代码构建为 .NET 6.0 时,代码被编译为

    string two = "2";
    DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(8, 1);
    defaultInterpolatedStringHandler.AppendLiteral(" 3");
    defaultInterpolatedStringHandler.AppendFormatted(two);
    defaultInterpolatedStringHandler.AppendLiteral("1 ");
    defaultInterpolatedStringHandler.AppendLiteral(" 4");
    defaultInterpolatedStringHandler.AppendLiteral(" 5");
    string test = defaultInterpolatedStringHandler.ToStringAndClear();
    Console.WriteLine(test);

产生输出 321 4 5

但这是特定于使用 Visual Studio 构建 .NET 6.0 的。构建时使用dotnet build 代码编译为

    string two = "2";
    string test = "1 " + two + " 3 4 5";
    Console.WriteLine(test);

这会产生正确的输出。


推荐阅读