Convert String to custom Class Type in Vb.net

流过昼夜 提交于 2019-12-08 00:42:39

问题


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.

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

Class MyStringType

    Dim str As String

End Class
Dim s As MyStringType = "mystringgoeshere"

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

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.

Any ideas? thx~


回答1:


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

from last link:

Widening conversions always succeed at run time and never incur data loss. Examples are Single to Double, Char to String, and a derived type to its base type.

so try something like this

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



回答2:


just change ur code little bit like this :

Class MyStringType 
    Dim str As String 
    Sub New(ByVal str1 As String) 
         str = str 
    End Sub 
End Class

Dim s As New MyStringType("abhi")



回答3:


what you should do is

Class MyStringType

    Dim str As String

End Class
Dim s As MyStringType 
s.str = "mystringgoeshere"



回答4:


It sounds like you want to subclass System.String. This is a fundamental of OOP programming. Inheritance is PRETTY important.

http://en.m.wikipedia.org/wiki/Inheritance_(object-oriented_programming)



来源:https://stackoverflow.com/questions/13263524/convert-string-to-custom-class-type-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!