Converting object of a class to of another one

前端 未结 7 765
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-28 08:33

I have two classes which have are nearly equal except the data types stored in them. One class contains all double values while other contains all float values.



        
7条回答
  •  萌比男神i
    2020-12-28 08:46

    Use a conversion operator:

    public static explicit operator FloatClass (DoubleClass c) {
       FloatCass fc = new FloatClass();
       fc.X = (float) c.X;
       fc.Y = (float) c.Y;
       fc.Z = (float) c.Z;
       return fc;
    }
    

    And then just use it:

    var convertedObject = (FloatClass) doubleObject;
    

    Edit

    I changed the operator to explicit instead of implicit since I was using a FloatClass cast in the example. I prefer to use explicit over implicit so it forces me to confirm what type the object will be converted to (to me it means less distraction errors + readability).

    However, you can use implicit conversion and then you would just need to do:

    var convertedObject = doubleObject;
    

    Reference

提交回复
热议问题