c# - 如果使用接口(interface),类是否应该始终严格实现接口(interface)

标签 c# design-patterns class

问这个问题的更好方法是举个例子如下 这两种方法的优缺点是什么?一个总是比另一个更好还是在特定情况下?如果使用 Approach1,那么使用接口(interface)是没有实际意义的,对吧?因为无论如何任何人都可以访问公共(public)方法?

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, User user, 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, User user, string category)
  {
   //do some logic here...
  }

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

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

最佳答案

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

显式接口(interface)实现还意味着您不能覆盖接口(interface)方法——您必须在任何子类中重新实现接口(interface)。基本上它最终变得非常复杂 - 所以我会尽可能避免它。

一个最后注意事项:显式接口(interface)实现也是plays badly with dynamic in C# 4 .

关于c# - 如果使用接口(interface),类是否应该始终严格实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3814748/

相关文章:

c# - 最小起订量验证 : Expected invocation on the mock at least once, 失败异常但从未执行

c# - 如何测试 RoutedUICommand?

javascript - 立即调用函数表达式 (IIFE) 与非立即调用函数表达式

java - 无法序列化 ArrayList

c++ - 如何在 C++ 中创建一个作为另一个类的 vector 的类?

c# - 如何使用将 DBcontext 对象传递给继承 GenericRepository<T> 抽象类的实体的构造函数

c# - 根据在 C# 中创建的日期搜索文件

微服务架构中的 Elasticsearch

java - 通过其实例调用接口(interface)或抽象类方法

python - 在 Python 中调用函数之前检查函数是否引发 NotImplementedError