gpt4 book ai didi

c# - Visual Studio 2015 和 IFormatProvider 中的字符串插值 (CA1305)

转载 作者:IT王子 更新时间:2023-10-29 04:12:53 25 4
gpt4 key购买 nike

Visual Studio 2015 中新的字符串插值样式是这样的:

Dim s = $"Hello {name}"

但如果我使用它,代码分析会告诉我我破坏了 CA1305: Specify IFormatProvider

以前我是这样做的:

Dim s = String.Format(Globalization.CultureInfo.InvariantCulture, "Hello {0}", name)

但是新样式怎么办呢?

我必须提到我正在寻找 .Net 4.5.2 的解决方案(for .Net 4.6 dcastro has the answer)

最佳答案

您将使用 System.FormattableStringSystem.IFormattable 类:

IFormattable ifs = (IFormattable)$"Hello, {name}";
System.FormattableString fss = $"Hello, {name}";

// pass null to use the format as it was used upon initialization above.
string ifresult = ifs.ToString(null, CultureInfo.InvariantCulture);
string fsresult = fss.ToString(CultureInfo.InvariantCulture);

您需要针对 Framework 4.6 进行编译,因为 IFormattableFormattableString 是旧版本中不存在的类。因此,如果您的目标是较旧版本的 .NET 框架,则无法在不触发错误的情况下使用插值语法。

除非你应用一些技巧( adapted to compile against 4.6 RTM from Jon Skeet's gistforked to my own account )。只需将一个类文件添加到您的项目中,其中包含:

Update

There is now also a Nuget package available that will provide the same functionality to your project (thanks for bringing this to my attention @habakuk).

install-package StringInterpolationBridge

或者,如果您想在不向产品添加额外组件的情况下实现相同的目的,请将以下代码添加到您的项目中:

namespace System.Runtime.CompilerServices
{
internal class FormattableStringFactory
{
public static FormattableString Create(string messageFormat, params object[] args)
{
return new FormattableString(messageFormat, args);
}
}
}

namespace System
{
internal class FormattableString : IFormattable
{
private readonly string messageFormat;
private readonly object[] args;

public FormattableString(string messageFormat, object[] args)
{
this.messageFormat = messageFormat;
this.args = args;
}

public override string ToString()
{
return string.Format(messageFormat, args);
}

public string ToString(string format, IFormatProvider formatProvider)
{
return string.Format(formatProvider, format ?? messageFormat, args);
}

public string ToString(IFormatProvider formatProvider)
{
return string.Format(formatProvider, messageFormat, args);
}
}
}

参见:

关于c# - Visual Studio 2015 和 IFormatProvider 中的字符串插值 (CA1305),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32076823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com