我寫了這個擴展的StringBuilder在VB.NET:如何在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
我試着將它移植到C#(我在慢慢學習/自學C#),但我一直不成功迄今爲止:
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);
}
}
}
當我在App_Code文件夾中有這個文件,我得到了以下錯誤消息:
編譯器錯誤信息: CS1112:做不使用'System.Runtime.CompilerServices.ExtensionAttribute'。改爲使用'this'關鍵字。
我不確定這是什麼意思,因爲如果我用'this'替換'[Extension()]',與擴展相關的唯一的東西是'ExtensionAttribute',但那不工作。
有人知道我失蹤了嗎?
謝謝!
不相關的擴展問題,但我在你的最後一個方法使用的ParamArray的VB版本中看到。 C#中的等效語法是params string [] args。 – dahlbyk 2009-07-24 15:53:29