C# 隐式转换

2021-06-20 01:03

阅读:531

标签:ext   隐式   ace   operator   show   []   task   col   exp   

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

 

C# 隐式转换

标签:ext   隐式   ace   operator   show   []   task   col   exp   

原文地址:https://www.cnblogs.com/namejr/p/10269333.html


评论


亲,登录后才可以留言!