你如何在vb.net中继承StringBuilder?

时间:2008-10-07 16:10:48

标签: vb.net stringbuilder

我想将自己的成员添加到StringBuilder类中,但是当我去创建它时,IntelliSense不会提起它。

public class myStringBuilder()
    Inherits System.Text.[StringBuilder should be here]
    ....
end class

甚至可能吗?感谢

6 个答案:

答案 0 :(得分:16)

StringBuilderNotInheritable(在C#中又名sealed),因此您无法从中获取。您可以尝试在自己的课程中包装StringBuilder,或者考虑使用extension methods代替。

答案 1 :(得分:3)

不,StringBuilderNotInheritable类。您可以尝试包装StringBuilder实例,但不能从中继承。如果您使用的是.NET 3.5,也可以使用extension methods

答案 2 :(得分:2)

这是我想出来的,对于那些好奇的人:

Imports System.Runtime.CompilerServices
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

答案 3 :(得分:1)

StringBuilder是一个密封的类......所以不允许继承。

答案 4 :(得分:1)

StringBuilder是密封的。你无法继承它。

答案 5 :(得分:1)

如果您使用的是早期版本的.Net,您可以编写基本相同的StringBuilderExtensions类,然后显式调用静态方法。

使用.Net 3.5:myStringBuilder.MyExtensionMethod(etc...);

Pre .Net 3.5:StringBuilderExtensions.MyExtensionMethod(myStringBuilder, etc...);