自定义类型,派生自 String [英] Custom Type, derived from String
问题描述
我正在处理一个 API,它以以下格式响应我的 POST 请求:
I am dealing with an API which responds to my POST requests under the following format:
Base64String:AnotherBase64String:Another:Etc
Base64String:AnotherBase64String:Another:Etc
因此,我有一些 Functions
和 Extensions
接受/返回以下格式的字符串:
I have therefore some Functions
and Extensions
which take/return strings under the following format:
- Base64 字符串
- Base64DoubleDotsBase64 字符串(见上文)
事情变得相当混乱,从某种意义上说,当一个函数接受一个 String
作为输入时,需要一些时间(阅读函数文档)来检查 String
应该是一个字符串,或者一个 Base64 字符串等.Strings
Extensions
的智能感知也被入侵了.
Things are getting quite messy, in the sense that when a function takes a String
as an input, it takes some time (reading the Function doc) to check if the String
should be a string, or a Base64 string, etc. The intellisense for Strings
Extensions
is also getting invaded.
我正在考虑派生两个新的 Types
以便事情更容易.
I am considering deriving two new Types
so that things are easier.
String
是 NotInheritable
,所以我倾向于使用以下内容:
String
is NotInheritable
, so I am enclined to use the following:
Class Base64String
Dim str As String
End Class
可以吗?看起来很简单(也很漂亮),我很紧张.
Is that OK? It seems so simple (and beautiful), I am nervous.
PS:我的 Base64 字符串不需要任何操作,例如连接.唯一需要的扩展将是定制的.但是,如果有办法让字符串的本机扩展工作,我很想知道(出于好奇).
PS: my Base64 Strings will not require any operations such as concatenation. The only extensions required will be custom made. However, if there is a way to get the native extensions for string to work, I would be interested to know (out of curiosity).
推荐答案
Mark Hall 的帖子在 他的帖子中提到了 Widening,这正是我需要的:
Mark Hall's post mentions Widening in his post, which is just what I needed:
Public Class Base64String
Private _String As String
Private Sub New(ByVal value As String)
Me._string = value
End Sub
Public Shared Widening Operator CType(ByVal value As String) As Base64String
Return New Base64String(value)
End Operator
Public Overrides Function ToString() As String
Return _String
End Function
Public Shared Operator &(ByVal s1 As Base64String, s2 As Base64String) As Base64String
Dim temp As String = s1._String & s2._String
Return New Base64String(temp)
End Operator
End Class
像这样使用:
Dim MyString As Base64String = "abcd"
Console.WriteLine(MyString)
这篇关于自定义类型,派生自 String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!