C# 隐式转换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dog dog1 = new Dog("jack");
            dog1.ShowName();
            // 使用隐式转换
            Cat cat1 = dog1;
            cat1.ShowName();
            // 使用显式转换
            Dog dog2 = (Dog)cat1;
            dog2.ShowName();
        }
    }
    public class Dog
    {
        private string Name;
        public Dog(string dname)
        {
            Name = dname;
        }
        public void ShowName()
        {
            Console.WriteLine("这是一条狗:{0}", Name);
        }
        // 隐式转换,将狗的类转换为猫的类
        public static implicit operator Cat(Dog dog)
        {
            return new Cat(dog.Name);
        }
    }
    public class Cat
    {
        private string Cname;
        public Cat(string cname)
        {
            Cname = cname;
        }
        public void ShowName()
        {
            Console.WriteLine("这是一条猫:{0}", Cname);
        }
        // 显式转换
        public static explicit operator Dog(Cat cat)
        {
            return new Dog(cat.Cname);
        }
    }
}

 

猜你喜欢

转载自www.cnblogs.com/namejr/p/10269333.html
0条评论
添加一条新回复
  
今日推荐