输入Casting Issue,我无法使用类型成员

时间:2013-12-26 19:13:06

标签: .net vb.net types casting intellisense

我编写了一个自己的类型,当我尝试将自己的类型转换为对象时,我想使用该类型具有的属性成员。

我尝试使用CtypeDirectCast/TryCast,但Intellisense没有向我显示类型成员,所以我无法使用它。

所以......有办法做到这一点吗?这是我正在使用的代码(参见注释行):

private sub SomeSub

    ' I declare a variable as Object/Undefined type, I couldn't change this.
    Dim SomeVar As Object = Nothing

    select case SomeEnumValue

        case SomeEnum.Value1
            SomeVar = CStr("Some String") ' A String type

        case SomeEnum.Value2
            SomeVar = CLng(1L) ' A Long type

        case SomeEnum.Value3
            SomeVar = CType(SomeVar, MyOwntype) ' My Own Type

            ' So here I would like to be able to use the object members,
            ' instead of the need to use Ctype like this:

            SomeControl.Text = CType(SomeVar, MyOwntype).Property

    end select

end sub

3 个答案:

答案 0 :(得分:2)

您可以将CType结果存储在本地变量中,并使用它来访问您的属性

Dim myObj As MyOwnType = CType(SomeVar, MyOwnType)
SomeControl.Text = myObj.Property

答案 1 :(得分:1)

请记住,转换引用类型对象实际上根本不会转换对象。所有的铸造都是为了改变你通过它访问物体的镜头(界面)。考虑到这一点,以下几行完全没用:

SomeVar = CType(action, MyOwntype)

SomeVarAs Object,因此,在设置SomeVar之前,首先将对象强制转换为任何特定类型,这是毫无意义的。一旦SomeVar指向它,它将查看As Object,无论之前查看/引用它的界面如何。

执行您想要执行的操作的方法是创建特定类型的新变量并将该变量设置为该对象。如果您有Option Strict On,就像您最有可能的那样,您需要在设置变量时进行转换。但是,一旦设置了变量,就可以通过该变量(具有完整的智能感知)访问对象,而无需每次都重新投射。例如:

Dim mySpecificVar As MyOwnType = DirectCast(action, MyOwnType)
SomeControl.Text = mySpecificVar.Property
' ...

答案 2 :(得分:0)

如果您想使用这些属性,则必须将其强制转换为MyOwnType类型,如:

SomeControl.Text = DirectCast(SomeVar, MyOwntype).Property

您不能单独使用SomeVar,因为它的类型Object没有自定义属性。