将一个类的对象转换为另一个类的对象 [英] Converting object of a class to of another one

查看:50
本文介绍了将一个类的对象转换为另一个类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了存储在其中的数据类型外,我有两个几乎相等的类.一个类包含所有双精度值,而另一个包含所有浮点值.

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.

class DoubleClass
{
    double X;
    double Y;
    double Z;
}

class FloatClass
{
    float X;
    float Y;
    float Z;
}

现在我有一个 DoubleClass 点,我想将其转换为 FloatClass.

Now I have a point of DoubleClass which I want to convert to FloatClass.

var doubleObject = new DoubleClass();

var convertedObject = (FloatClass)doubleObject; // TODO: This

一种简单的方法是创建一个方法来创建一个新的 FloatClass 对象,填充所有值并返回它.有没有其他有效的方法来做到这一点.

One simple way is to make a method which creates a new FloatClass object, fills all values and return it. Is there any other efficient way to do this.

推荐答案

使用转换运算符:

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;
}

然后就用它吧:

var convertedObject = (FloatClass) doubleObject;

编辑

我将运算符更改为 explicit 而不是 implicit 因为我在示例中使用了 FloatClass 强制转换.我更喜欢使用 explicit 而不是 implicit 所以它迫使我确认对象将被转换为 的类型(对我来说这意味着更少的干扰错误 + 可读性).

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).

但是,您可以使用 implicit 转换,然后您只需要这样做:

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

var convertedObject = doubleObject;

参考

这篇关于将一个类的对象转换为另一个类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆