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

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

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值