在C#中的数据类型之间进行转换

Jim*_*mbo 11 c# generics types casting object

我有(例如)类型A的对象,我希望能够转换为类型B(类似于如何将其转换int为a float)

数据类型A和B是我自己的.

是否可以定义进行此转换的规则?

int a = 1;
float b = (float)a;
int c = (int)b;
Run Code Online (Sandbox Code Playgroud)

Dan*_*haw 14

是的,这可以使用C#运算符重载.显式隐式有两个版本.

这是一个完整的例子:

class Program
{
    static void Main(string[] args)
    {
        A a1 = new A(1);
        B b1 = a1;

        B b2 = new B(1.1);
        A a2 = (A)b2;
    }
}

class A
{
    public int Foo;

    public A(int foo)
    {
        this.Foo = foo;
    }

    public static implicit operator B(A a)
    {
        return new B(a.Foo);
    }
}

class B
{
    public double Bar;

    public B(double bar)
    {
        this.Bar = bar;
    }

    public static explicit operator A(B b)
    {
        return new A((int)b.Bar);
    }
}
Run Code Online (Sandbox Code Playgroud)

类型A可以隐式转换为类型B,但类型B必须显式转换为类型A.