c# - 向界面添加新功能

标签 c# interface overloading

我需要为现有接口(interface)上的函数创建重载,而不影响当前实现或使用该接口(interface)的任何组件(理想情况下)。

我想我有几个选择:

简化 原始界面:

public interface IServerComponent
{
    bool Add(int a, int b);
}

我可以将新的重载函数添加到接口(interface)并强制每个实现该接口(interface)的类实现新函数。

public interface IServerComponent
{
    bool Add(int a, int b);
    bool Add(int a, int b, int c);
}

或者我可以创建一个实现原始接口(interface)的新接口(interface)。然后其他使用原始接口(interface)的类不需要更改,任何新类都可以实现新接口(interface)...

public interface IServerComponent2 : IServerComponent
{
    bool Add(int a, int b, int c);
}

这种情况的最佳做法是什么?还有其他选择吗?

谢谢

最佳答案

如果新方法可以用旧方法表示,则可以使用扩展方法:

// Original interface
public interface IServerComponent 
{ 
  bool Add(int a, int b, int c); 
} 

// New overload
public static class MyServerMethods
{
  public static bool Add(this IServerComponent component, int a, int b)
  {
    return component.Add(a, b, 0);
  }
}

如果方法不能那样表达(即它们确实需要由组件本身实现),那么我建议定义一个新接口(interface)。这种方法具有最大的向后兼容性。

关于c# - 向界面添加新功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3256075/

相关文章:

c++ - 什么接口(interface)会将 cstrings、数组和其他类型复制到相同类型的实例?

c++ - 按字母顺序将对象插入 vector C++

c# - 长轮询停止其他请求 1 或 2 分钟

c# - Rhino Mocks 在 Debug模式下表现出不同的行为

c# - 从 htmldocument :HTMLAgilityPack 中删除 html 节点

c# - 将json字符串反序列化为对象C#.net

java - 为什么Java接口(interface)可以在这些代码中被实例化?

java - compareTo 方法不会编译

java - Lambda 重载方法

c# - 在类定义中强制偏好重载?