我写了这个扩展的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