vb.netでStringBuilderをどのように継承しますか?
-
05-07-2019 - |
質問
自分のメンバーをStringBuilderクラスに追加したいのですが、作成するときにIntelliSenseが起動しません。
public class myStringBuilder()
Inherits System.Text.[StringBuilder should be here]
....
end class
それも可能ですか?ありがとう
解決
StringBuilder
は NotInheritable
(C#では sealed
)なので、そこから派生することはできません。独自のクラスで StringBuilder
をラップするか、代わりに拡張メソッド。
他のヒント
いいえ、 StringBuilder は NotInheritable クラス。 StringBuilder インスタンスをラップすることもできますが、それを継承しません。 .NETを使用している場合は、拡張メソッドも使用できます。 3.5。
好奇心urious盛な人のために、これが私が思いついたものです:
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
StringBuilderは封印されたクラスであるため、継承は許可されません。
StringBuilderはシールされています。継承することはできません。
.Netの以前のバージョンを使用している場合、基本的に同じStringBuilderExtensionsクラスを記述してから、代わりに静的メソッドを明示的に呼び出すことができます。
.Net 3.5の場合: myStringBuilder.MyExtensionMethod(etc ...);
.Net 3.5以前: StringBuilderExtensions.MyExtensionMethod(myStringBuilderなど...);
所属していません StackOverflow