Ich schrieb diese Erweiterung für Stringbuilder in VB.NET:Wie erstellen Sie eine Erweiterung in C#?
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("{0}{1}", String.Format(format, arg0), 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("{0}{1}", String.Format(format, arg0, arg1), 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("{0}{1}", String.Format(format, arg0, arg1, arg2), 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("{0}{1}", String.Format(format, args), ControlChars.NewLine)
End Sub
End Module
ich es in C# versuchte Portierung (ich langsam lerne/mich C# Lehre), aber ich habe bisher nicht erfolgreich gewesen:
using System.Runtime.CompilerServices;
namespace myExtensions
{
public static class sbExtension
{
[Extension()]
public static void AppendFormattedLine(this System.Text.StringBuilder oStr, string format, string arg0)
{
oStr.AppendFormat("{0}{1}", string.Format(format, arg0), Environment.NewLine);
}
[Extension()]
public static void AppendFormattedLine(this System.Text.StringBuilder oStr, string format, string arg0, string arg1)
{
oStr.AppendFormat("{0}{1}", string.Format(format, arg0, arg1), Environment.NewLine);
}
[Extension()]
public static void AppendFormattedLine(this System.Text.StringBuilder oStr, string format, string arg0, string arg1, string arg2)
{
oStr.AppendFormat("{0}{1}", string.Format(format, arg0, arg1, arg2), Environment.NewLine);
}
[Extension()]
public static void AppendFormattedLine(this System.Text.StringBuilder oStr, string format, string[] args)
{
oStr.AppendFormat("{0}{1}", string.Format(format, args), Environment.NewLine);
}
}
}
Wenn ich diese Datei in meinem Ordner App_Code habe, bekomme ich folgende Fehlermeldung:
Compiler-Fehlermeldung: CS1112: Do Verwenden Sie 'System.Runtime.CompilerServices.ExtensionAttribute' nicht. Verwenden Sie stattdessen das Schlüsselwort 'this'.
Ich bin nicht sicher, was damit es bedeutet, denn wenn ich ersetzen ‚[Extension()]‘ mit ‚this‘, das einzige, was zu einer Verlängerung verbunden ist, ist ‚Extension‘, aber das bedeutet nicht arbeite entweder.
Weiß jemand, was ich vermisse?
Danke!
nicht an Ihre Neben Frage bezogen, aber ich sehe in der VB-Version ParamArray in der letzten Methode verwenden. Die entsprechende Syntax in C# lautet params string [] args. – dahlbyk