【问题标题】:String Interpolation C#字符串插值 C#
【发布时间】:2019-01-02 11:08:05
【问题描述】:

如果我们可以将字符串的 temp_data 存储在一个变量中并对其使用插值?

var name = "John";

var temp_data = "Hi {name}";

var result_data = $temp_data;

如果除了string.Format()string.Replace() 之外还有其他可能的解决方案

【问题讨论】:

  • “使用插值”是什么意思?
  • 不完全确定你的意思,但我想你想要这个:$"Hi {name}"
  • var result_data = temp_data.Replace("{name}", name); 怎么样?
  • 因为对我来说 temp_data 将从数据库中获取数据
  • 插值是常规 String.Format编译时间 语法糖。您需要使用它(或其他一些模板代码)。

标签: c# asp.net


【解决方案1】:

如果您希望将消息存储为外部资源,则需要使用 string.Format 而不是字符串插值,插值字符串必须在编译时作为字符串文字完整地存在。

您还需要确保消息中包含的变量数量与调用 string.format 的代码中的变量数量相匹配,否则将无法正确转置。

例如,这是使用资源文件;

var message = string.Format(Strings.ErrorMessage, value1, value2);

Strings.ErrorMessage 将包含;

“这是错误 {0} 和消息 {1}”

【讨论】:

  • @Leogiciel 不,因为如我的回答中所述,当使用代码外部的消息(数据库/资源​​文件)时,您不能这样做。
  • 你说得对,我绝对误解了这个解释不清的用例。 String.Format 是正确的解决方案,+1 赞。
【解决方案2】:

你可以使用$ - string interpolation (C# Reference) https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

【讨论】:

    【解决方案3】:

    你可以这样使用

    double speedOfLight = 299792.458;
    FormattableString message = $"The speed of light is {speedOfLight:N3} km/s.";
    
    System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
    string messageInCurrentCulture = message.ToString();
    
    var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
    string messageInSpecificCulture = message.ToString(specificCulture);
    
    string messageInInvariantCulture = FormattableString.Invariant(message);
    
    Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
    Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");
    Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");
    

    【讨论】:

      【解决方案4】:

      使用 C#6,你可以完全按照你写的去做,没有错字:

      var name = "John";
      
      var temp_data = $"Hi {name}";
      
      var result_data = temp_data;
      
      Console.log(result_data);
      

      将返回“Hi John”;)

      【讨论】:

      • 不回答问题,消息(temp_data)需要来自数据库/外部资源以及创建另一个字符串(result_data)的目的是什么
      • 你在哪里读到一些关于数据库/外部资源的东西??创建另一个字符串只是为了保留问题示例形式......
      • 见下面问题的cmets
      • 我还要补充一点,您的示例无论如何都没有使用字符串插值,result_data 的值是“Hi {name”)
      • 然后随意发布一个使用字符串插值从外部资源“和”加载消息的工作示例
      猜你喜欢
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多