implicit关键字和explicit关键字

explicit关键字

explicit关键字的作用是强制转换用户自定义的显式类型转换运算符。通常前面通用static后面用operator,一般是把当前类型转换为另一个类型(将原类型转换为目标类型)。
举个例子:

class A
{
    public A(float f)
    {
        p = f;
        Console.WriteLine("p of A is " + p.ToString());
    }
    public float p { get; private set; }
    public static explicit operator B(A a)
    {
        return new B(a.p * 2);
    }
}
class B
{
    public B(float f)
    {
        p = f;
        Console.WriteLine("p of B is " + p.ToString());
    }
    public float p { get; private set; }
    public static explicit operator A(B b)
    {
        return new A(b.p * 10f);
    }
}

调用方式如下:

A a = new A(10);
B b = (B)a;

控制台输出如下:

p of A is 10
p of B is 20

implicit关键字

implicit关键字和explicit关键字类似,它实现自定义类型的隐式类型转换。
还是上面的例子:

class A
{
    public A(float f)
    {
        p = f;
        Console.WriteLine("p of A is " + p.ToString());
    }
    public float p { get; private set; }
    public static implicit operator B(A a)
    {
        return new B(a.p * 2);
    }
}
class B
{
    public B(float f)
    {
        p = f;
        Console.WriteLine("p of B is " + p.ToString());
    }
    public float p { get; private set; }
    public static implicit operator A(B b)
    {
        return new A(b.p * 10f);
    }
}

调用方式如下:

A a = new A(10);
B b = a;

控制台输出如下:

p of A is 10
p of B is 20
Tips

注意的是A类到B类的”显式“和”隐式“ 转换只能定义一个,不能同时定义两个。

posted @ 2019-01-23 15:19  lsy1991  阅读(228)  评论(0编辑  收藏  举报