【发布时间】:2019-07-17 16:12:42
【问题描述】:
我想要达到的目标如下。
我有一个类似
的界面interface ISomething<T>
{
void Input(T item);
IEnumerable<T> Outputs();
}
和类似的层次结构
interface IFoo { }
interface IBar : IFoo { }
interface IBaz : IFoo { }
我希望能够通过ISomething<IFoo> 引用ISomething<IBaz> 和ISomething<IBar>,这样我就可以编写类似的方法
void ProcessFoos(ISomething<IFoo> somethings)
{
foreach (var something in somethings)
{
var outputs = something.Outputs();
// do something with outputs
}
}
其中somethings 可以是ISomething<IBar>s 和ISomething<IBaz>s 的组合。
考虑到语言限制,这不可能吗?
如果没有,我该如何重新设计?
编辑:这是我所说的更好的例子
public class Program
{
public static void Main()
{
IBar<IX> x = new Bar<Y>() { };
// ^^^ Cannot implicitly convert type 'Bar<Y>' to 'IBar<IX>'. An explicit conversion exists (are you missing a cast?)
}
}
public interface IBar<T> where T : IX
{
void In(T item);
T Out { get; }
}
public class Bar<T> : IBar<T> where T : IX
{
public void In(T item) { }
public T Out { get { return default(T); } }
}
public interface IX { }
public class Y : IX { }
【问题讨论】:
-
我也尝试过这样做,但没有成功,但如果您将接口声明为
in,然后在您的代码类中显式实现它,它确实有效。 -
@theMayer 看到我的编辑
-
您的编辑是一个全新的问题。
标签: c# .net oop inheritance