c# - 如何使用 Format ("blah {0}", someValue) 签名(如 string.format)实现 MyMethod()

标签 c# .net string arguments string-formatting

String.Format 和 StringBuilder(通过 AppendFormat 方法)允许调用者将值泵入他们准备好的字符串中,例如:

string temp = string.Format("Item {0} of {1}, Record Id: {2} started...",
  itemCounter.ToString(),
  totalItemsToProcess.ToString(),
  myRecord.RecordId);
MyMethod(temp);

但与其构建一个字符串并将其传递给“MyMethod()”,我宁愿有一个人们这样称呼的重载:

MyMethod("Item {0} of {1}, Record Id: {2} started...",
  itemCounter.ToString(),
  totalItemsToProcess.ToString(),
  myRecord.RecordId);

您将如何实现? 有什么我可以利用的,还是我必须编写一堆自定义代码?

最佳答案

这很琐碎,但是参数的用法不那么琐碎:

static string MyMethod( string format, params object[] paramList )
{
    return string.Format(format, paramList);
}

关于c# - 如何使用 Format ("blah {0}", someValue) 签名(如 string.format)实现 MyMethod(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5814188/

相关文章:

c# - 在循环中创建对象

c# - 如何通过 Roslyn 查找基类的命名空间

c# - 通过字符串列的最大值和最小值查找数据行中的值是否相等

c++ - 移动数组中字符串的位置

Java使用正则表达式分割将字符串放入数组中

c# - 如果存在则删除子串

c# - Visual Studio 2017 : "Object reference not set to an instance of an object" while loading the project

c# - 获取 System.Drawing.Font 宽度?

c# - 要在 c# 库 : delegate with byref type 中使用的 F# 函数

c# - 在 OOXML 中使用大二进制段的问题