如何将VB.NET中的扩展名移植到C#?

And*_*ers 1 c# vb.net stringbuilder extension-methods

我在VB.NET中为StringBuilder写了一个扩展来添加一个AppendFormattedLine方法(所以我不必使用其中一个参数来换行符号):

Imports System.Runtime.CompilerServices
Public Module sbExtension
    <Extension()> _
    Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _
                                   ByVal format As String, _
                                   ByVal arg0 As Object)
        oStr.AppendFormat(format, arg0).Append(ControlChars.NewLine)
    End Sub
    <Extension()> _
    Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _
                                   ByVal format As String, ByVal arg0 As Object, _
                                   ByVal arg1 As Object)
        oStr.AppendFormat(format, arg0, arg1).Append(ControlChars.NewLine)
    End Sub
    <Extension()> _
    Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _
                                   ByVal format As String, _
                                   ByVal arg0 As Object, _
                                   ByVal arg1 As Object, _
                                   ByVal arg2 As Object)
        oStr.AppendFormat(format, arg0, arg1, arg2).Append(ControlChars.NewLine)
    End Sub
    <Extension()> _
   Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _
                                  ByVal format As String, _
                                  ByVal ParamArray args() As Object)
        oStr.AppendFormat(format, args).Append(ControlChars.NewLine)
    End Sub
End Module
Run Code Online (Sandbox Code Playgroud)

Joe*_*orn 7

我不会那样嵌套这些string.Format()电话.

您是否知道string.Format()在幕后创建一个新的StringBuilder并调用它的AppendFormat()方法?以第一种方法为例,这应该更有效:

sb.AppendFormat(format, arg0).Append(Environment.NewLine);
Run Code Online (Sandbox Code Playgroud)

您也应该对VB代码进行相同的更改.