转换一类的对象到另一个的 [英] Converting object of a class to of another one
问题描述
我有两个类具有相同,除了存储在其中的数据类型几乎相等。一类包含所有的双重价值,而其他包含所有浮点值。
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;
修改
我改变了运营商明确
而不是隐
,因为我使用的是 FloatClass
投中的示例。我更喜欢使用明确
在隐
所以它迫使我确定什么类型的对象将转换成的 (对我来说意味着更少分心错误+可读性)。的
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;
的参考
这篇关于转换一类的对象到另一个的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!