# 自定义类型间转换,该如何处理

www.MyException.Cn  网友分享于：2013-01-13  浏览：10次

C#提供自定义类型之间互相强制转换的机制吗？

------解决方案--------------------

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

*****************************************************************************

http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html
------解决方案--------------------
http://msdn2.microsoft.com/zh-cn/library/zk2z37d3(VS.80).aspx
------解决方案--------------------

[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]