StringBuilder Append and AppendLine give different results for Enum
When using a string builder, I get expected results from the append and append line functions when using an enum is the input, but when the enum is boxed the append line and append function give differing results.
Can anyone tell me what may be behind this?
Code output:
Append Enum: 1
Append Enum To String: One
Append Line Enum: 1
Append Line Enum To String: One
Append Object: One
Append Object To String: One
Append Line Object: 1
Append Line Object To String: One
Code:
Public Enum eTest
One = 1
Two = 2
End Enum
Sub Main()
Dim sb As New System.Text.StringBuilder()
Dim x = eTest.One
sb.App开发者_C百科end("Append Enum: ").Append(x).AppendLine()
sb.Append("Append Enum To String: ").Append(x.ToString()).AppendLine()
sb.Append("Append Line Enum: ").AppendLine(x)
sb.Append("Append Line Enum To String: ").AppendLine(x.ToString())
Dim o As Object = x
sb.Append("Append Object: ").Append(o).AppendLine()
sb.Append("Append Object To String: ").Append(o.ToString()).AppendLine()
sb.Append("Append Line Object: ").AppendLine(o)
sb.Append("Append Line Object To String: ").AppendLine(o.ToString())
Console.WriteLine(sb.ToString())
'===============================
Console.ReadKey()
End Sub
This line
sb.Append("Append Object: ").Append(o).AppendLine()
causes o.ToString()
to be appended to the instance of StringBuilder
and that is the difference. Of course, that call just passes through to the boxed instance of your enum and this is why you see One
for this invocation.
This is because you are invoking the overload StringBuilder.Append(object)
which will just invoke o.ToString()
on the passed in instance of object. This is explicitly in the documentation:
The
Append
method calls theObject.ToString
method to get the string representation ofvalue
. Ifvalue
isnull
, no changes are made to theStringBuilder
object.
On the other hand, when you call
sb.Append("Append Enum: ").Append(x).AppendLine()
where x
is an instance of an enum, x
will be implicitly converted to an instance of int
which will call the overload StringBuilder.Append(int)
.
Note that this is specific to VB.NET. C# will not implicitly convert x
to an int
when choosing which overload of StringBuilder.Append
to invoke; it will invoke StringBuilder.Append(object)
.
精彩评论