Converting object of a class to of another one

前端 未结 7 699
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  有刺的猬
    2020-12-28 08:42

    You could add an implicit type conversion operator:

    public class DoubleClass
    {
        public double X;
        public double Y;
        public double Z;
    
        public static implicit operator FloatClass(DoubleClass d)
        {
            return new FloatClass { X = (float)d.X, Y = (float)d.Y, Z = (float)d.Z };
        }
    }
    

    Now this works:

    DoubleClass doubleObject = new DoubleClass();
    FloatClass convertedObject = doubleObject;
    

提交回复
热议问题