2013-02-18 136 views
0

比方说,我有:如何从继承类型的对象中获取BaseType类型的对象?

Class Vehicle 
    Public Property NumberOfWheels As Integer 
End Class 

Class Bicycle 
    Inherits Vehicle 

End Class 

我做的:

Dim b = New Bicycle() With {.NumberOfWheels = 2} 
Dim v As Vehicle = CType(b, Vehicle) 

v仍然Bicycle当我调试的代码,并用鼠标悬停的对象。 如何从Bicycle类型的对象中获取类型为Vehicle的对象?我必须手动执行吗?

+1

为什么你需要?根据定义,“Bicycle”*是“Vehicle”。 – 2013-02-18 14:54:19

+0

我需要它,因为我尝试序列化对象,而我的WCF服务期望'Vehicle'。我读了''KnownType'属性,但它不适用于我... – 2013-02-18 14:55:29

+0

如果服务在它的合同中要求一个'Vehicle',并且您传递了一个'Bicycle',它应该可以正常工作。其他的东西可能是错的。要回答您的原始问题,是的,您需要手动完成一些工作,所以最好在这种情况下解决主要问题而不是症状。 – 2013-02-18 14:58:41

回答

0

我要给你明显的解决方案:

Class Bicycle 
    Inherits Vehicle 

    Public Shared Widening Operator CType(value As Bicycle) As Vehicle 
     Return New Vehicle With {.NumberOfWheels = value.NumberOfWheels} 
    End Operator 

End Class 

但是也弹出一个编译器错误:

Conversion operators cannot convert from a type to its base type

MSDN上做一个快速搜索带来了如下解释:

At compile time, Visual Basic considers a predefined conversion to exist from any reference type to any type in its inheritance hierarchy, that is, any type from which it derives or which derives from it. Such a conversion might fail at run time, but the compiler cannot predict run-time results, so it allows any such conversion to compile.

简而言之,我认为您需要在01上实施并为从其派生的每个类提供自定义实现。