日期:2014-05-18  浏览次数:20662 次

自定义类型间转换
C#提供自定义类型之间互相强制转换的机制吗?
譬如我定义了两个类型,他们所占用的内存空间是一样的,只是存储的格式不一样而已,能不能象其他语言一样可以强制转换?
多谢先!

------解决方案--------------------
下面的示例提供 Fahrenheit 和 Celsius 类,它们中的每一个都为另一个提供显式转换运算符。
using System;
class Celsius
{
public Celsius(float temp)
{
degrees = temp;
}
public static explicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
}
public float Degrees
{
get { return degrees; }
}
private float degrees;
}

class Fahrenheit
{
public Fahrenheit(float temp)
{
degrees = temp;
}
public static explicit operator Celsius(Fahrenheit f)
{
return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
}
public float Degrees
{
get { return degrees; }
}
private float degrees;
}

class MainClass
{
static void Main()
{
Fahrenheit f = new Fahrenheit(100.0f);
Console.Write("{0} fahrenheit", f.Degrees);
Celsius c = (Celsius)f;
Console.Write(" = {0} celsius", c.Degrees);
Fahrenheit f2 = (Fahrenheit)c;
Console.WriteLine(" = {0} fahrenheit", f2.Degrees);
}
}
  
*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码) 

http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html
------解决方案--------------------
http://msdn2.microsoft.com/zh-cn/library/zk2z37d3(VS.80).aspx
------解决方案--------------------
貌似记得要两个类为父子关系时才能转,当然这个父子可以是多级的.祖先和玄孙.

你的两个类型之间互转,不如在类里写动态方法 toOther() 返回要转过去的类型,里面的值对应关系自己写.
[code=C#]
public class A
{
public char A;

public B ToB()
{
B b = new B();
b.B = Convert.ToByte(A);
return b;
}
}

class B
{
public byte B;

public A toA()
{
A a = new A();
a.A = Convert.ToChar(B);
return a;
}
}
code]