中将字符串转换为自定义类类型

中将字符串转换为自定义类类型

本文介绍了在 Vb.net 中将字符串转换为自定义类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现的大多数搜索结果都与我正在寻找的结果相反,所以这是我的问题:

Most of the search results I've found have turned up to be the opposite of what I'm looking for so here's my question:

我正在尝试将系统类型转换为我自己的自定义类型,但正如我所提到的,我的搜索结果并不有效,并且与我正在寻找的结果相反.

I'm trying to convert System types into custom types of my own but as I mentioned, my search results have not been effective and give me the opposite of what i'm looking for.

假设我有一个mystringgoeshere"字符串和一个类:

Say I have a String of "mystringgoeshere" and a class like:

Class MyStringType

    Dim str As String

End Class
Dim s As MyStringType = "mystringgoeshere"

我收到此错误 {Value of type 'String' 无法转换为 'Project1.MyStringType'.}

And i get this error {Value of type 'String' cannot be converted to 'Project1.MyStringType'.}

我还没有任何代码,因为我不知道如何实现这一点,但基本上我想要做的是使用我在代码中拥有的方法设置s"对象的str"字符串块上面.我试过使用new(data as String)"子例程,但它不适用于我正在尝试的方法.

I don't have any code yet really because I have no idea how to achieve this, but essentially what I want to do is set the "s" object's "str" string using a method like what i have in the code block above. I've tried using a "new(data as String)" subroutine, but it doesn't work with what i am trying.

有什么想法吗?谢谢~

推荐答案

看这个 VBCity 关于创建自定义类型的文章 它正在使用 加宽运算符.

Looking at this VBCity Article on creating Custom Types It is using the Widening Operator.

来自上一个链接:

扩大转换总是在运行时成功并且不会导致数据丢失.示例是 Single 到 Double、Char 到 String,以及派生类型到其基类型.

所以尝试这样的事情

Public Class Form1

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Dim s As MyStringType = "mystringgoeshere"
        Dim s1 As MyStringType = "Hello"
        Dim s2 As MyStringType = s1 + s
    End Sub
End Class

Class MyStringType
    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 MyStringType
        Return New MyStringType(value)
    End Operator
    Public Overrides Function ToString() As String
        Return _string
    End Function
    Public Shared Operator +(ByVal s1 As MyStringType, s2 As MyStringType) As MyStringType
        Dim temp As String = s1._string + s2._string
        Return New MyStringType(temp)
    End Operator
End Class

这篇关于在 Vb.net 中将字符串转换为自定义类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:38