编写一个asp.net mvc应用程序,我有这样的东西…… Public Class AA'... has some variables...End ClassPublic Class BBInherits AAPublic ExtraVariable As Integer ' just adds another variable and thats it!End Class 那么,现在在我
Public Class AA '... has some variables... End Class Public Class BB Inherits AA Public ExtraVariable As Integer ' just adds another variable and thats it! End Class
那么,现在在我的程序中,我只想将类型AA的对象复制到BB类型的空变量中?
这样做是有意义的,因为我希望AA类型对象中的所有字段都被复制到新创建的BB类型对象,而BB类型对象中的ExtraVariable我将(稍后)只为它分配一个值(之后)副本)在我自己的时间!
我知道将BB类型复制到AA类型是不合适的,因为会丢失数据!
但我试图将AA复制到BB,我已经使用DirectCast和CType来做到这一点,并且我一直“无法投射”错误!
注意:我正在使用vb.net(但可以读取c#,没问题)
正如anon所说,您可能希望将AA传递给BB的构造函数,您可以在其中复制所有元素:public class AA
{
//some variables
}
public class BB : AA
{
public BB(AA aa)
{
//Set BBs variables to those in AA
someVariable= aa.someVariable
}
public int SomeExtraProperty{get;set;}
}
但显然你可以使用任何可以重用的继承构造函数,如果合适的话你可以重用它们.
编辑
基于上面的一些评论,您还可以:
public class BB : AA
{
private AA _aa;
public BB(AA aa)
{
//Set BBs variables to those in AA
_aa=aa;
}
public int SomeExtraProperty{get;set;}
//override inherted members and just delegate to the internal object
public override int SomeMethod()
{
return _aa.SomeMethod();
}
}
或者可能去Decorator Pattern
