【发布时间】:2013-04-11 13:16:14
【问题描述】:
我有这个想要的类层次结构:
interface IClass
{
string print(IClass item);
}
class MyClass : IClass
{
// invalid interface implementation
// parameter type should be IClass not MyClass
string print(MyClass item)
{ return item.ToString(); }
}
我尝试通过使用泛型类型来解决接口实现问题,但没有成功:
interface IClass
{
string print<T>(T item) where T : IClass;
}
class MyClass : IClass
{
string print<T>(T item) where T : MyClass
{ return item.ToString(); }
}
我该怎么办?
【问题讨论】:
-
你应该使接口本身通用,并为实现类提供所需的类型。
-
打印方法中不带参数如何让每个子类将IClass实现注入到contructor或serter中。
-
toString 方法继承自 Object,那么为什么你真的需要
print(MyClass item)而不仅仅是print(Object item)?你隐藏这个方法吗? -
这只是我真实类层次结构的简化示例。
标签: c# class-hierarchy