Nei*_*ith 0 .net c# extension-methods
我正在为string.Format写一个扩展名(我之前没有遇到任何问题.)
我的扩展名:
public static string FormatWith(this string source, params object[] args) {
source.ThrowIfNull("source");
return string.Format(source, args);
}
Run Code Online (Sandbox Code Playgroud)
我的测试:
[TestMethod]
public void FormatWith_ShouldReturnCorrectResult_FromValidArgs() {
var expected = "testing 123";
var actual = "test".FormatWith("ing", " ", 123);
Assert.AreEqual(expected, actual);
}
Run Code Online (Sandbox Code Playgroud)
在我的测试中,在调用FormatWith之后,实际应该是"测试123",但它只是"测试".
我测试的消息:
Assert.AreEqual failed. Expected:<testing123>. Actual:<test>.
Run Code Online (Sandbox Code Playgroud)
我已经尝试将除string之外的类型传递给扩展名,但结果没有改变.而且我确定source.ThrowIfNull不会抛出异常.
什么给出了什么?我忽略了什么吗?一个很好的答案将向我展示FormatWith的工作实现,并解释为什么我的实现不起作用.
编辑:我是个白痴,完全忘了{0},{1} ......我也是每天使用它.定时器启动时会接受第一个答案.多谢你们.
我不是.NET人,但我可以阅读API文档:http://www.dotnetperls.com/string-format
如果我没弄错,你的源字符串需要显式地将你的参数添加到字符串中.
var actual = "test{0}{1}{2}".FormatWith("ing", " ", 123);
Run Code Online (Sandbox Code Playgroud)
随意纠正我的.NET人员.