【问题标题】:Variable in the dynamic string in C#C#中动态字符串中的变量
【发布时间】:2017-09-26 21:09:28
【问题描述】:

我有一个通过 SMS 发送消息的模块。如果消息是静态的,我可以将变量放在字符串中,但是用户请求消息可以随意更改。

我创建了这个变量

  1. 公司名称
  2. 客户姓名
  3. 账单号码
  4. 付款

例子:

来自{公司}{CustomerName} 先生/女士,您好,您的帐单号码是 {BillNumber},总付款为 {Payment}。我们想通知您 物品已完成并可以收集。

我当前的代码适用于静态消息,

string messageSms = "From " +Company+ ". Hi Mr/Mrs "+{CustomerName}+", your bill number is "+{BillNumber}+" with a total payment of "+{Payment}+". We want to inform you the items has been completed and ready for collection.";

但是如何处理动态消息呢?如何检测字符串中的变量并在变量上设置数据?

我也关注这个article,但帮助不大。

【问题讨论】:

  • 你能举一个期望输入/输出的例子吗?
  • 您能否详细说明您要处理的案件?

标签: c# string


【解决方案1】:

假设我理解,我认为String.Inject 课程可能会有所帮助。图片一个名为String.Format

"Hello, {company}!".Inject(new { company = "StackOverflow" });
// "Hello, StackOverflow!"

另一个好处是您可以拥有一个硬编码模型并直接引用它的属性。例如

class Contact
{
    string FirstName;
    string LastName;
}

String greeting = "Mr. {FirstName} {LastName}, Welcome to the site ...";
String result = greeting.Inject(new Contact
{
    FirstName = "Brad",
    LastName = "Christie"
});

【讨论】:

  • 我可以知道允许使用 String.Inject 属性的框架吗?我正在使用 String.Inject 属性不可用的 3.5 版
  • @Chuki2:您需要在项目中包含该页面上列出的class,然后将其添加为using 语句。
  • @BradChristie,对不起,我没有意识到这一点。让我试试
  • @BradChristie,简单而真棒.. 感谢您的帮助!
【解决方案2】:
var newString = messageSms.Replace("{Company}", CompanyName)
                          .Replace("{CustomerName}", CustomerName) // ...etc

应该这样做。

【讨论】:

    【解决方案3】:

    您也可以在 C# 6.0 中使用 interpolated strings

    var messageSms = $"From {companyName}. Hi {customerName}, your bill number is {billNumber} with a total payment of {payment}.";
    

    【讨论】:

      【解决方案4】:

      我会采用以下方法:

      string Company;
      string CustomerName;
      string BillNumber;
      string Payment;
      
      string messageSms = $@"
      From {Company}. Hi Mr/Mrs {CustomerName}, your bill number is {BillNumber} 
      with a total payment of {Payment}. We want to inform you the items has been 
      completed and ready for collection.
      ";
      

      【讨论】:

        【解决方案5】:

        试试String.Format方法,例如:

        string messageSms = String.Format("From {0}. Hi ..{1}, Your..{2} with..{3}. We..", 
                                          CompanyName, CustomerName, BillNumber, Payment);
        

        【讨论】:

        • 这不符合 OP 的“命名参数”要求。
        • 是的,确实如此,作为程序员很容易理解,但对用户来说却不是。这就是为什么我需要使用命名参数。顺便感谢您的帮助。
        【解决方案6】:

        我认为实现这一目标的最简单方法(您没有澄清您的问题)是使用string.Format()。 像这样使用它:

        string company = ...;
        string name= ...;
        string billNr= ...;
        string payment= ...;
        string output = string.Format("From {0}. Hi Mr/Mrs {1}, your bill number is {2} with a total payment of {3}. We want to inform you the items has been completed and ready for collection.", company, name, billNr, payment);
        

        【讨论】:

        • 对于用户来说,这种方式不友好,容易混淆。感谢您的帮助
        【解决方案7】:

        为什么不改用StringBuilder

        StringBuilder stringBuilder = new StringBuilder("From {Company}.Hi Mr/Mrs {CustomerName}, your bill number is {BillNumber} with a total payment of {Payment}. We want to inform you the items has been completed and ready for collection.");
        stringBuilder.Replace("{Company}",CompanyName);
        stringBuilder.Replace("{CustomerName}",CustomerName);
        stringBuilder.Replace("{BillNumber}",BillNumber);
        stringBuilder.Replace("{Payment}",Payment);
        string messageSms = stringBuilder.ToString();
        

        【讨论】:

          【解决方案8】:

          要创建一个可重用的解决方案,您可以首先声明一个包含替换值作为属性的对象。在这种情况下,我只是声明了一个匿名对象,但普通类也可以工作:

          var data = new {
            Company = "Stack Overflow",
            CustomerName = "Martin Liversage",
            BillNumber = 123456,
            Payment = 1234.567M.ToString("N2")
          };
          

          注意我如何“作弊”并将字符串分配给Payment。数字和日期/时间格式始终是一个复杂的问题,我决定在声明数据对象时预先进行格式设置。相反,您可以在格式化引擎中构建一些或多或少复杂的格式化规则。

          拥有一个具有属性的数据对象,我可以构建一个名称/值对的字典:

          var dictionary = data
            .GetType()
            .GetProperties()
            .ToDictionary(
              propertyInfo => propertyInfo.Name,
              propertyInfo => propertyInfo.GetValue(data, null)
            );
          

          假设format 包含格式化模板,那么只需遍历字典中的元素即可创建替换字符串:

          var buffer = new StringBuilder(format);
          foreach (var name in dictionary.Keys) {
            var value = dictionary[name].ToString();
            buffer.Replace("{" + name + "}", value);
          }
          var message = buffer.ToString();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-08-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-07-11
            • 1970-01-01
            • 1970-01-01
            • 2020-03-30
            相关资源
            最近更新 更多