c#中的接口查询(QueryInterface)

接口查询(QueryInterface)

       一个类可以有多个接口,声明了接口变量并且指向一个对象的时候,这个变量只能使用该接口内的方法和属性,而不能访问其他接口中的方法和属性。但接口查询很方便的让我们在一个类中的不同接口间进行切换。

using System;
namespace ConsoleApp1
{
        interface IEat
        {
            void Eat();
        }
        interface IRun
        {
            void Run();
        }
        class Person : IEat, IRun
        {
            public void Eat()
            {
                Console.WriteLine("我喜欢吃东西");
            }
            public void Run()
            {
                Console.WriteLine("我喜欢跑步");
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                IEat eat = new Person();
                eat.Eat();
                IRun run = eat as IRun;
                run.Run();

                Console.ReadKey();
            }
        }
}

猜你喜欢

转载自blog.csdn.net/qq_40323256/article/details/83045018