C#隐式实现接口成员与显示实现接口成员

转自https://blog.csdn.net/sirenxiaohuayuan/article/details/50426682
C#在类中实现接口。实现接口的类必须包含该接口的所有成员的实现代码,且都是公共的。实现接口成员有隐式实现和显式实现两种方法。

  1. 隐式实现

如下图所示,类MyClass隐式地实现了接口IMyInterface的DoSomething和DoSomethingElse两个方法。对于隐式实现的成员,既可以通过类对象实例来访问,也可以通过接口来访问。如Main函数所示,两种调用方法都能成功。

namespace Ch10Ex03
{
class Program
{
public interface IMyInterface
{
void DoSomething();
void DoSomethingElse();
}

    public class MyClass : IMyInterface
    {
        public void DoSomething()
        {
            Console.WriteLine("DoSomething\n");
        }

        public void DoSomethingElse()
        {
            Console.WriteLine("DoSomethingElse\n");
        }
    }

    static void Main(string[] args)
    {
        //通过类对象实例访问
          MyClass myObj1 = new MyClass();
        myObj1.DoSomething();
        myObj1.DoSomethingElse();

        //通过接口来访问
          MyClass      myObj2    = new MyClass();
        IMyInterface myIntface = myObj2;
        myIntface.DoSomething();
        myIntface.DoSomethingElse();

        Console.ReadKey();
    }
}

}

  1. 显式实现

如下图所示,类MyClass显式地实现了接口IMyInterface的DoSomething方法,隐式的实现了DoSomethingElse方法。对于显式实现的成员,只能通过接口来访问,不能使用类对象来访问。注意显式实现接口方法的时候不需要加public、private等关键词。

namespace Ch10Ex03
{
class Program
{
public interface IMyInterface
{
void DoSomething();
void DoSomethingElse();
}

    public class MyClass : IMyInterface
    {
        void IMyInterface.DoSomething()
        {
            Console.WriteLine("DoSomething\n");
        }

        public void DoSomethingElse()
        {
            Console.WriteLine("DoSomethingElse\n");
        }
    }

    static void Main(string[] args)
    {
        //通过接口来访问
          MyClass      myObj     = new MyClass();
        IMyInterface myIntface = myObj;
        myIntface.DoSomething();
        myIntface.DoSomethingElse();

        Console.ReadKey();
    }
}

}

猜你喜欢

转载自blog.csdn.net/weixin_42826294/article/details/81902988