加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如果使用接口,则类始终严格实现接口

发布时间:2020-12-15 04:28:01 所属栏目:百科 来源:网络整理
导读:提出这个问题的更好方法是如下例子 这两种方法的优点和缺点是什么?一个总是优于另一个或在特定情况下?如果使用Approach1,使用界面会没有意义吗?既然任何人都可以访问公共方法呢? public interface IDoSomething{ void Method1(string operation,User use
提出这个问题的更好方法是如下例子
这两种方法的优点和缺点是什么?一个总是优于另一个或在特定情况下?如果使用Approach1,使用界面会没有意义吗?既然任何人都可以访问公共方法呢?
public interface IDoSomething
{
  void Method1(string operation,User user,string category)
  void Method2(string operation,User user)
  void Method3(string operation)
}

//Approach1
Class A: IDoSomething
{                              
  public void Method1(string operation,string category)
  {
   //do some db logic here...
  }

  public void Method2(string operation,User user)
  {
    Method1(operation,user,"General");
  }

  public void Method3(string operation)
  {
    Method1(operation,User.GetDefaultUser(),"General");
  }
}

要么

//Approach2
Class A: IDoSomething
{                              
  void IDoSomething.Method1(string operation,string category)
  {
   //do some logic here...
  }

  void IDoSomething.Method2(string operation,User user)
  {
    (this as IDoSomething).Method1(operation,"General");
  }

  void IDoSomething.Method3(string operation)
  {
    (this as IDoSomething).Method1(operation,"General");
  }
}

解决方法

您正在寻找描述第二种方法的短语是显式接口实现.就个人而言,我大部分时间都不会使用它.您需要以不同的方式实现具有相同成员签名的不同接口,或者如果您希望限制某些成员仅在处理接口类型的表达式时可见时,这很有用…但是如果对于无论你的调用者具有什么样的具体类型,并且需要调用一些特定于类型的方法和一些接口方法.如果不将此类方法强制转换为接口类型,您甚至无法在同一个类中看到显式实现的方法.

显式接口实现还意味着您不能覆盖接口方法 – 您必须在任何子类中重新实现接口.基本上它最终会变得非常复杂 – 所以如果可能的话我会避免它.

最后一点说明:显式接口实现也是plays badly with dynamic in C# 4.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读