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不会有任何影响。请问用什么方法实现相同的功能?
...
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不会有任何影响。请问用什么方法实现相同的功能?
Inherits IClock
...
End InterfaceClass WristWatch
Implements IAlarmClock, ITimer
...
End Class
但是你的对象实际上是基类A (=new A) ,可是A的实例怎么会有子类的方法ToString呢?
jiangsheng(蒋晟.Net[MVP]) :感谢。我也想是用接口实现,但具体还不知道怎么实现。现在实际情况是:有一个基类,其中一个方法是返回基类的一个实例。还有若干个子类,子类的数量未定,根据项目的开发可能还会增加,所以不可能在基类的方法中一一枚举。现在情况是子类都是通过基类的那个方法来创建,于是就出现上面的问题。其实子类并没有更改基类的数据,只是不同的子类某个属性的叫法不同。比如有一个文件系统类,有一个属性是Name,派生类文件类中多了一个FileName属性,其实返回的是基类的Name;而同样是派生类文件夹类就会是FolderName属性,返回的还是基类的Name。我想这样使用时更加清晰。象这样的情况用接口具体是什么思路?怎样才能使以后将出现的子类也用同样的方法创建?
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)
Class [ClassName]
Inherits A
End Class
这样看起来派生类和A是一模一样的了。但是有语句:Dim V As [派生类名称] = New A 就会出错。我是想解决这个问题。
能不能帮我解决http://community.csdn.net/Expert/topic/4608/4608358.xml?temp=.6571466
这个问题啊