我需要为现有接口(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/