您可以引入非通用接口IFoo:
public interface IFoo
{
RecordType Type { get; set; }
}
它由泛型Foo类实现:
public class Foo<T> : IFoo
{
public T Value { get; set; }
}
并创建一个工厂方法,该方法根据记录类型创建一个Foo实例:
public static IFoo CreateFoo(RecordType type)
{
switch (type)
{
case RecordType.Bool: return new Foo<bool>();
// ...
}
}
IFoo foo = CreateFoo(RecordType.Bool);
if (foo.Type == RecordType.Bool)
{
Foo<bool> boolFoo = (Foo<bool>)foo;
bool value = boolFoo.Value;
}
如果有一个方法可以处理Foo对象,例如:
void DoIt<T>(IEnumerable<Foo<T>> foos)
{
foreach (Foo<T> foo in foos)
{
Qux(foo.Value);
}
}
IEnumerable<IFoo> foos = // ...
DoIt<bool>(foos.OfType<Foo<bool>>());
因此,基本上,您使用Foo<T>当您在编译时知道T,而IFoo如果您只在运行时知道T。IFoo需要检查才能将其转换为Foo<T>对于运行时的一些T。