[英]What is the difference between implicit and explicit StringBuilder.ToString() method calls?
I just wrote a small Unit Test in which I used a StringBuilder()
.我刚刚编写了一个小型单元测试,其中使用了
StringBuilder()
。
var stringBuilder = new StringBuilder();
stringBuilder.Append("Foo");
Assert.AreEqual(stringBuilder, "Foo");
This Test will fail.此测试将失败。
Expected: <Foo>
But was: "Foo"
But if I change the Assert to但是,如果我将 Assert 更改为
Assert.AreEqual(stringBuilder.ToString(), "Foo");
the test will pass.测试将通过。
So, what is the difference between the implicit call and the explicit call of the ToString()
method?那么,
ToString()
方法的隐式调用和显式调用有什么区别呢? Or/And what are these Brackets ( <>
) standing for?或者/这些括号(
<>
)代表什么?
In your first example, you are testing if your StringBuilder
instance is equal to the string, which will fail.在您的第一个示例中,您正在测试
StringBuilder
实例是否等于字符串,这将失败。
In your second one, you are testing if the result of the call to ToString()
(which is a string) is equal to the other string.在您的第二个中,您正在测试调用
ToString()
(它是一个字符串)的结果是否等于另一个字符串。
The bracktes (<>) are NUnits way to indicate that it got an non-string object, but to display the message, NUnit calls ToString()
on that object.括号 (<>) 是 NUnit 的方式,用于指示它获得了一个非字符串对象,但为了显示消息,NUnit 对该对象调用
ToString()
。
Expected: <Foo> But was: "Foo"
So <Foo>
is an object that returns Foo
on a call to ToString()
, whereas "Foo"
is just a String
Foo .所以
<Foo>
是一个在调用ToString()
返回Foo
的对象,而"Foo"
只是一个String
Foo 。
MSTest would show you a different message, which would be more clear: MSTest 会向您显示不同的消息,这会更清楚:
Expected:<Foo (System.Text.StringBuilder)>. Actual:<Foo (System.String)>.
In the first version there is no implicit call to ToString This only happens in methods like Console.WriteLine.在第一个版本中,没有对 ToString 的隐式调用这只会发生在像 Console.WriteLine 这样的方法中。
So what actually happens is that you are equating a stringbuilder object to a string object.因此,实际发生的是您将 stringbuilder 对象等同于 string 对象。 Even the types do not match :-)
即使类型不匹配:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.