【发布时间】:2019-01-10 08:54:27
【问题描述】:
我有两个来自第三方的具有相同功能的接口。由于这是第三方接口,我无法附加父接口。
public interface IInterface1 {
int Open(string stringName);
}
public interface IInterface2 {
int Open(string stringName);
}
我想将它们传递给基类
public class MyClass : BassClass<IInterfaceWithOpenFunction>
这样我就可以以相同的方式在两个类上执行相同的功能。
public class BassClass<T> Where T : IInterfaceWithOpenFunction, new()
{
private T item;
public BaseClass(string stringName)
{
item = new T();
item.open(stringName);
我不想让项目动态化,因为我想保持智能感知,我该如何实现?
不知何故,IInterfaceWithOpenFunction 需要消耗其他接口的函数 open,同时允许我传入所需的接口来实现。
【问题讨论】:
-
就语言而言,这些方法并不是“完全相同的功能”,正是因为它们位于不同的接口中。 C# 没有鸭子类型(除非您已经丢弃了动态)。某种类型的检查/转换/适配器将是不可避免的。有很多方法可以给猫换皮,例如,使用
Func<string, int>委托和一些扩展方法。 -
当我不得不处理这种类型的问题时,我通常最终会编写具有通用接口的包装类。
-
@juharr,我不拥有这些接口,那么如何将通用接口附加到它们?我希望在运行时不要这样做。
-
@JeroenMostert
C# does not have duck typing (barring dynamics)和foreach, example here -
@Flater:技术上正确确实是最好的正确。我将把我的评论修改为“它没有用户可控的鸭子打字”。
标签: c# generics inheritance interface base-class