How to copy an object that is inherited from an im object trying to copy?

Writing an asp.net mvc application and I have something like this ...

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

So now in my program I just want to copy an object of type AA to an empty variable of type BB?

it makes sense to do this, since I expect that all fields in an object of type A will be copied to a newly created object of type BB, and ExtraVariable in an object of type BB I will (will) just assign it a value later (after the copy) in due time!

I know that copying type BB to type AA would be inappropriate since data was lost!

But I'm trying to copy AA to BB, I used both DirectCast, and CTypeto do this, and I keep getting the error "impossible to execute" !!!

. vb.net( #, )

+3
5

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

+1

, .

, , , , BB, AA .

+5

, .

: #?.

        public class AA
        {
            public string name;
        }
        public class BB : AA 
        {
            public BB(AA aa)
            {
                name = aa.name;
            }
        }
+1

, .

BB AA, , , BB.

AA BB , AA BB. , , , .

, , , "":

bb.Value1 = aa.Value1
bb.Value2 = aa.Value2
bb.Value3 = aa.Value3

.

0

, , , , , .

, , . -, , , ,

ie

:

public class BaseObject 
{

}

public class InheritedObject : BaseObject
{

}

public class BaseObjectConsumer()
{
    Consumer(BaseObject base);
}

public class InheritedObjectConsumer()
{

}

:

InheritedObject io = new InheritedObject();
BaseObject bo = new BaseObject();

BaseObjectConsumer(io); //this is possible as the InheritedObject is being 'viewed' as a BaseObject

InheritedObjectConsumer(bo); //Not as simple, as the Base object is not necessarily an Inherited object, so we can't cast 'up'
0

Source: https://habr.com/ru/post/1732917/


All Articles