c# - 代码在 .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>";
解决方案
这似乎是 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);
这会产生正确的输出。
推荐阅读
- node.js - 如何动态更新 jsonb 列
- c# - 无法使用 .NET 标准库通过 TLS 连接到 IBM MQ
- wordpress - Wordpress 网站标题未从选项卡中删除
- node.js - 尝试调用云函数设置 Firestore 时出错
- python - 在 DataFrame 中删除两个日期列匹配的行,否则,更改另一列中的值
- c - 在execl()函数ic C语言中使用rm linux命令
- java - 如何使函数添加到 main 中的字符串而不替换字符串中的先前数据?
- sql - 在解析预期的块集合时
,但找到了“?” - c++ - 变量在 for 循环语句期间不会更改其值
- dictionary - Pyspark 地图功能仅打印第一个 roe