我只想确认一下我对C#中泛型的理解。这是在我工作过的几个代码库中出现的,其中泛型基类用于创建类型安全的派生实例。这是我所说的一个非常简单的例子
public class SomeClass<T>
{
public virtual void SomeMethod(){ }
}
public class DeriveFrom :SomeClass<string>
{
public override void SomeMethod()
{
base.SomeMethod();
}
}
当我想以多态的方式使用派生实例时,问题就出现了。
public class ClientCode
{
public void DoSomethingClienty()
{
Factory factory = new Factory();
//Doesn't compile because SomeClass needs a type parameter!
SomeClass someInstance = factory.Create();
someInstance.SomeMethod();
}
}
似乎一旦您将泛型引入继承层次结构或接口中,您就不能再以多态的方式使用该类族,除非它本身是内部的。这是真的吗?
发布于 2009-11-29 14:55:48
据我所知,使用代码不需要泛型类的细节(也就是说,它不依赖于T
是什么)。那么,为什么不引入SomeClass<T>
将实现接口,并使用该接口的实例。
例如:
public interface ISome
{
void SomeMethod();
}
public class SomeClass<T>: ISome
{
public virtual void SomeMethod(){ }
}
public void DoSomethingClienty()
{
Factory factory = new Factory();
ISome someInstance = factory.Create();
someInstance.SomeMethod();
}
现在,SomeClass<T>
的子类可以在不同的T
上以不同的方式操作,但是使用代码不会改变。
发布于 2009-11-29 16:19:51
我更喜欢使用抽象类作为所有泛型类型的基础。
public abstract class SomeClass
{
public abstract void SomeMethod();
}
public class SomeClass<T> : SomeClass
{
public override void SomeMethod() { }
}
public class DeriveFrom<String> : SomeClass<String>
{
public override void SomeMethod() { base.SomeMethod(); }
}
发布于 2012-03-10 06:11:47
public Class ReflectionReport<T>
{
// This class uses Reflection to produce column-based grids for reporting.
// However, you need a type in order to know what the columns are.
}
... so, in another class you have...
public Class ReflectionReportProject {
ReflectionReport<Thang> thangReport = new ReflectionReport<Thang>();
ReflectionReport<Thong> thongReport = new ReflectionReport<Thong>();
... some more stuff ...
// Now, you want to pass off all of the reports to be processed at one time....
public ReflectionReport<????>[] ProvideReports()
{
return new ReflectionReport<????>[] { thangReport, thongReport } ;
}
}
https://stackoverflow.com/questions/1814851
复制相似问题