문제

I am sure this is a simple question for you guys but I don't know what this developer is doing.

name = String.Format(MyStringBuilder + "");

If I convert this to VB I get the message "operator + is not defined for types system.text.stringbuilder and string". Same thing if I use &.

도움이 되었습니까?

해결책

In the strictest sense, MyStringBuilder in the original code could be a null instance, at which point making an explicit call to .ToString() would throw an exception. The code sample provided would execute properly, however. In VB, you may want to say

Dim name As String
If MyStringBuilder Is Nothing Then
   name = String.Empty
Else
   name = MyStringBuilder.ToString()
End If

다른 팁

It looks as if the person who wrote it is attempting to force an implicit conversion of MyStringBuilder to a string using the + operator in conjuction with the empty string.

To perform this assignment in VB you only need:

name = MyStringBuilder.ToString()

That doesn't make sense to me because AFAICT passing only one argument to string.format doesn't do anything.

Adding "" to the stringbuilder just coerces it to a string.

name = MyStringBuilder.ToString(); would be how I'd do this in C#. Converting that statement to VB should be loads easier.

Use MyStringBuilder.ToString(). That will fix the problem.

You're trying to concatenate a StringBuilder object and String together - that wouldn't work :)

name = String.Format(MyStringBuilder.ToString() + "");

This should compile correctly.

In VB.NET you would use a "&" instead of a "+"

This line:

name = String.Format(MyStringBuilder + "");

Is causing an implicit cast of MyStringBuilder to string (using the ToString() method) in order to use the "+" operator. It's the same as:

name = String.Format(MyStringBuilder.ToString() + "");

which is the same as

name = MyStringBuilder.ToString();

which becomes this in VB.NET:

name = MyStringBuilder.ToString()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top