Public Class A
    ...
  Public Name as String
End ClassPublic Class B
  Inherits A  Public Function ToString As String
    Return Name
  End Function
End Class现在有这样一个问题:
Dim C as B = New A
提示转换无效。当然,从理论上讲,肯定是这样结果,因为只能是从子类转换为父类,而不能从父类转换成子类。但实际上上面的例子如果可以转换对B不会有任何影响。请问用什么方法实现相同的功能?

解决方案 »

  1.   

    Interface IAlarmClock 
      Inherits IClock
      ...
    End InterfaceClass WristWatch 
      Implements IAlarmClock, ITimer 
       ...
    End Class 
      

  2.   

    Dim C as B = New AC的类型是B,那么C应该有方法ToString()吧
    但是你的对象实际上是基类A (=new A) ,可是A的实例怎么会有子类的方法ToString呢?
      

  3.   

    AntingZ(夕惕若):看来你没有明白问题的意思。
    jiangsheng(蒋晟.Net[MVP]) :感谢。我也想是用接口实现,但具体还不知道怎么实现。现在实际情况是:有一个基类,其中一个方法是返回基类的一个实例。还有若干个子类,子类的数量未定,根据项目的开发可能还会增加,所以不可能在基类的方法中一一枚举。现在情况是子类都是通过基类的那个方法来创建,于是就出现上面的问题。其实子类并没有更改基类的数据,只是不同的子类某个属性的叫法不同。比如有一个文件系统类,有一个属性是Name,派生类文件类中多了一个FileName属性,其实返回的是基类的Name;而同样是派生类文件夹类就会是FolderName属性,返回的还是基类的Name。我想这样使用时更加清晰。象这样的情况用接口具体是什么思路?怎样才能使以后将出现的子类也用同样的方法创建?
      

  4.   

    '定义基类接口
    Public Interface IBase
        Property Name() As String
    End Interface’派生文件类接口
    Public Interface IFile
        Inherits IBase
        Property FileName() As String
    End Interface‘文件夹接口
    Public Interface IFolder
        Inherits IBase
        Property FolderName() As String
    End InterfacePublic Class CBaseImp
        Implements IBase    Private strName As String    Public Property Name() As String Implements IBase.Name
            Get
                Return strName
            End Get
            Set(ByVal Value As String)
                strName = Value
            End Set
        End Property
    End ClassPublic Class CFileImp
        Inherits CBaseImp
        Implements IFile    Public Property FileName() As String Implements IFile.FileName
            Get
                Return MyBase.Name
            End Get
            Set(ByVal Value As String)        End Set
        End Property
    End ClassPublic Class CFolderImp
        Inherits CBaseImp
        Implements IFolder    Public Property FolderName() As String Implements IFolder.FolderName
            Get
                Return MyBase.Name
            End Get
            Set(ByVal Value As String)        End Set
        End Property
    End ClassDim pFile as IFile =New CFileImp
    Dim pFoler as IFolder =New CFolderImp
    如果每个派生类都需要对基类的某个方法进行重写,则可以将基类该方法声明为必须重写(MustOverride),同时基类也要声明为必须继承(MustInherit)
      

  5.   

    luiselouse(luiselouse) :非常感谢.不过看来你也没明白我的问题.举个例子吧,比如有一个类A,还有若干未知数量的派生类,这些派生类声明都是:
    Class [ClassName]
       Inherits A
    End Class
    这样看起来派生类和A是一模一样的了。但是有语句:Dim V As [派生类名称] = New A 就会出错。我是想解决这个问题。
      

  6.   

    关注!!!不过我不懂
    能不能帮我解决http://community.csdn.net/Expert/topic/4608/4608358.xml?temp=.6571466
    这个问题啊
      

  7.   

    建议楼主学习继承,虚函数的内容。你这么设计很不好。我曾看到wtl里用模板实现类似虚汗数功能的,但认为这样是垃圾。楼主别这么创意了。用正规方法好了。你这里,用接口和虚函数都可以。当然,到底使用接口还是虚函数,区别就在于你的这个函数声明是否需要重用,需要重用就写成接口,否则就写虚函数。