自定义类型转换是写在被转换的类中码?

来源:4-2 自定义转换

零零拾

2017-03-11 12:26

比如把狗转化成猫咪

是应该写在狗过的类中吗?

写回答 关注

1回答

  • zjuPeco
    2017-03-11 12:48:15
    已采纳

    对的。

    若在类Dog.cs中写下

    public static implicit operator Cat(Dog dog)
            {
                return new Cat(dog._name);
            }

    则在static void Main(string[] args)中可用

    Dog d1 = new Dog("Tom");
    Cat c1 = d1;

    实现狗到猫的隐式类型转换。


    若在类Cat.cs中写下

    public static explicit operator Dog(Cat cat)
            {
                return new Dog(cat._name);
            }

    则在static void Main(string[] args)中可用

    Cat c2 = new Cat("Bob");
    Dog d2 = (Dog)c2;

    实现猫到狗的显示转换。

    零零拾

    非常感谢!

    2017-03-11 12:53:20

    共 1 条回复 >

C#面向对象编程

本系列教程主要是,带你学习C#面向对象编程的编程思想、编程技巧

68599 学习 · 153 问题

查看课程

相似问题