预处理消息
如果您不想在每个 GetMessage(...) 调用中创建一个新数组,您可以插入 FirstValue 到消息在开头一次。然后GetMessage(...) 只使用string.Format(...) 的otherValues 参数。
Message 属性在 FirstValue 设置后初始化一次,例如在构造函数或 init 方法中,如下所示:
void InitMessage()
{
Message = String.Format(Message, FirstValue, "{0}", "{1}", "{2}", "{3}", "{4}");
}
InitMessage 方法用 FirstValue 初始化 Message 中的第一个索引,用“{index}”初始化其余索引,即“{0 }", "{1}", "{2}",... (允许有比消息索引更多的params 元素)。
现在 GetMessage 可以调用 String.Format 而无需像这样的任何数组操作:
public string GetMessage(params object[] otherValues)
{
return String.Format(Message, otherValues);
}
示例:
假定以下属性值:
this.Message = "First value is '{0}'. Other values are '{1}' and '{2}'." 和 this.FirstValue = "blue"。
InitMessage 将 Message 更改为:
"First value is 'blue'. Other values are '{0}' and '{1}'."。
GetMessage 调用
GetMessage("green", "red")
结果
"First value is 'blue'. Other values are 'green' and 'red'."。