Copying a class parameters
Monkey Forums/Monkey Programming/Copying a class parameters
| ||
Hi. Is there a command for copying all Class parameters to another. when you do ClassA=ClassB it only (as far as I know) copies the handles of the class. but if i want to create a cloned Class that gets all the parameters of the class that is being Cloned. Example: Class Car Field X# Field Y# End Class Danny:Car=New Car Danny.X=45 Goerge:Car=Danny Now when im doing Goerge=Danny It will only transfer the Handle But Goerge and Danny are still the same Class. I want A New Class Handle. I hope I am clear.. Cheers |
| ||
You need to make a copy constructor (at least, that's the neatest way to do it): The terminology I would use is that you want george and danny to be two separate instances of the same class. |
| ||
you should use reflection for this if there are more than a few fields I dont have time to make an example right now |
| ||
what reflection means? when ull have time please do post.. |
| ||
Strict Import reflection Class wizard Field health:Int Field name:String End Class Function copy_object:Object(obj:Object) Local clas:=GetClass(obj) Local copied_object:Object=clas.NewInstance() For Local thisfield:=Eachin clas.GetFields(True) Local fieldobj:Object=thisfield.GetValue(obj) Select thisfield.Type.Name Case "monkey.boxes.BoolObject" thisfield.SetValue(copied_object,fieldobj) Case "monkey.boxes.IntObject" thisfield.SetValue(copied_object,fieldobj) Case "monkey.boxes.StringObject" thisfield.SetValue(copied_object,fieldobj) Case "monkey.boxes.FloatObject" thisfield.SetValue(copied_object,fieldobj) End Select Next Return copied_object End Function Function Main:Int() Local first_wizard:wizard=New wizard first_wizard.name="Brian" first_wizard.health=98 Print first_wizard.name Print first_wizard.health Local second_wizard:wizard=wizard(copy_object(first_wizard)) Print second_wizard.name Print second_wizard.health Return 0 End Function this will copy any object that has basic fields if your objects have lists or collections as fields then lots more code will be needed |
| ||
great tnx |