How to create a class which inherits from a data type, specifically from Char data type? I just wan't to add one property to it. If it's not possible, are there any other 开发者_运维知识库ways to accomplish this?
I didn't think you could inherit from System types.
Remember an extension method can be only a Sub procedure or a Function procedure. You cannot define an extension property, field, or event.
Your options:
- Extension method (can only be a function or sub)
- A custom structure (use Reflector to make your own custom Char)
- A class that takes System.Char is input and allows you to store the Char and your extra property. You will need to implement your own
IsLetter
and the like.
Quick and dirty example (you may want to make this Static
by placing it in a Module
instead):
Class MyChar
Sub New()
End Sub
Sub New(byval input As System.Char)
Me.[Char] = input
End Sub
Sub New(byval input As String)
Me.Parse(input)
End Sub
Public Property [Char] As System.Char
Public Property ExtraProperty As String
Public ReadOnly Property IsLetter As Boolean
Get
return Me.[Char].IsLetter(Me.[Char])
End Get
End Property
Public Function Parse(ByVal input As String)
If (input Is Nothing) Then
Throw New ArgumentNullException("input")
End If
If (input.Length <> 1) Then
Throw New FormatException("Need a single character only")
End If
Me.[Char] = input.Chars(0)
End Function
End Class
Deriving from System.Char would be madness and a useless effort. Extension methods to the rescue.
精彩评论