How to copy object of class A to another object of class B?

Artur Skawina via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 28 06:54:09 PST 2015


On 01/28/15 10:44, zhmt via Digitalmars-d-learn wrote:
> I have a struct created by thrift:
> 
> struct Card {
>   long id;
>   string pwd;
>   long agentId;
>   bool valid;
>   long rmb;
>   long createDate;
>   long soldDate;
>   long chargeDate;
> 
>   mixin TStructHelpers!([
>     TFieldMeta(`id`, 1, TReq.OPTIONAL),
>     TFieldMeta(`pwd`, 2, TReq.OPTIONAL),
>     TFieldMeta(`agentId`, 3, TReq.OPTIONAL),
>     TFieldMeta(`valid`, 4, TReq.OPTIONAL),
>     TFieldMeta(`rmb`, 5, TReq.OPTIONAL),
>     TFieldMeta(`createDate`, 6, TReq.OPTIONAL),
>     TFieldMeta(`soldDate`, 7, TReq.OPTIONAL),
>     TFieldMeta(`chargeDate`, 8, TReq.OPTIONAL)
>   ]);
> }
> 
> and another class created for hibernated:
> 
> class Card
> {
>     import hibernated.core;
> 
>     @Id
>     @Generated
>     long id;
>     @UniqueKey
>     string pwd;
>     //index
>     long agentId;
>     bool valid;
>     long rmb;
>     long createDate;
>     long soldDate;
>     long chargeDate;
> }
> 
> 
> Sometime , I need to copy them:
> 
> thrift.Card tc;
> ....
> db.Card dc;
> 
> dc.id = tc.id;
> dc.pwd = tc.pwd;
> ...
> 
> 
> It is boring coding, I want a solution to copy them automatically:

You could just add a method to the db class:

    void fields(B)(auto ref B b) @property {
      foreach (I, _; typeof(this.tupleof))
         this.tupleof[I] = mixin(`b.`~__traits(identifier, this.tupleof[I]));
    }

then

   dc.fields = tc;

will work.

artur


More information about the Digitalmars-d-learn mailing list