string.Format不附加给定的args

时间:2014-02-14 21:03:09

标签: c# .net extension-methods

我正在为string.Format写一个扩展名(之前我没有遇到任何问题。)

我的扩展名:

    public static string FormatWith(this string source, params object[] args) {
        source.ThrowIfNull("source");

        return string.Format(source, args);
    }

我的测试:

    [TestMethod]
    public void FormatWith_ShouldReturnCorrectResult_FromValidArgs() {
        var expected = "testing 123";
        var actual = "test".FormatWith("ing", " ", 123);

        Assert.AreEqual(expected, actual);
    }

在我的测试中,在调用FormatWith之后,实际应该是“测试123”,但它只是“测试”。

我的测试消息:

    Assert.AreEqual failed. Expected:<testing123>. Actual:<test>.

我已尝试将除string之外的类型传递到扩展名中,但结果未更改。而且我确定source.ThrowIfNull不会抛出异常。

那是什么给出的?我忽略了什么吗?一个很好的答案将向我展示FormatWith的工作实现,并解释为什么我的实现不起作用。

编辑:我是个白痴,完全忘了{0},{1} ......我也是每天使用它。定时器启动时会接受第一个答案。谢谢你们。

3 个答案:

答案 0 :(得分:9)

我不是.NET人,但我可以阅读API文档:http://www.dotnetperls.com/string-format

如果我没弄错,你的源字符串需要明确地将你的参数添加到字符串中。

var actual = "test{0}{1}{2}".FormatWith("ing", " ", 123);

随意纠正我的.NET人员。

答案 1 :(得分:4)

您正在寻找String.ConcatString.Format不能像那样工作。只有你指定这样的参数:

string.Format("{0}, {1} ....",source,args);

你不能,因为你不知道参数的数量。所以你可以改用String.ConcatString.Join

答案 2 :(得分:0)

而不是像其他人建议的那样修改你对函数的使用,这里是一个FormatWith的实现,它将按你的意图工作:

public static string FormatWith(this string source, params object[] args)
{
    var arguments = new List<object> {source};
    arguments.AddRange(args);

    return String.Concat(arguments);
}