如果我理解正确的话,你想要一份清单Foo
具有不同类型的对象Output
是吧?由于这些输出具有不同的类型,因此无论如何您都必须在此处使用强制转换。
但是,以下想法可能会有所帮助。您声明一个名为的非泛型接口怎么样?IFoo
: ¹
public interface IFoo
{
object Output { get; }
}
然后在你的抽象类中实现它:
abstract class Foo<T> : IFoo
{
abstract T Output { get; }
object IFoo.Output { get { return Output; } }
}
然后你可以声明一个列表IFoo
s:
class Bar
{
List<IFoo> Foos;
}
访问食物时,您可以通过接口将输出检索为对象:
var myObject = Foos[0].Output; // type ‘object’
或者,如果您知道它只能是几种特定类型之一,则可以尝试发现真实类型:
if (Foos[0] is Foo<string>)
var myString = ((Foo<string>) Foos[0]).Output; // type ‘string’
您甚至可以根据类型进行过滤,例如:
// Type ‘IEnumerable<string>’ (rather than ‘IEnumerable<object>’)!
var stringFoos = Foos.OfType<Foo<string>>().Select(f => f.Output);
¹ You can also make this an abstract base class called Foo
and have Foo<T>
derive from it. In that case, you would need to mark Foo<T>.Output
with the new
keyword and use base.Output
to access the abstract base member.