传递一个类型列表,将类型限制为从一个特定父类派生的类,在c#中
问题描述:
我有一个面向对象的数据库的方法,它根据它们的类型创建表。传递一个类型列表,将类型限制为从一个特定父类派生的类,在c#中
我想能够发送一个类型列表来创建,但我希望将它们限制为仅从特定基类(MyBase)派生的类。
有没有办法可以在方法签名中要求这个? 而不是
CreateTables(IList<Type> tables)
我可以做的东西,将
CreateTables(IList<TypeWithBaseTypeMyBase> tables)
我知道我可以检查基类送过来每种类型的,但如果可能的话,我想这在编译时验证。
有什么建议吗?
答
你试过吗?
CreateTables(IList<MyBase> tables)
我想这就是你所要做的。
答
你可以做到以下几点:
CreateTables(IList<MyBase> tables)
{
// GetType will still return the original (child) type.
foreach(var item in tables)
{
var thisType = item.GetType();
// continue processing
}
}
答
为什么不只是改变签名:
CreateTables(IList<BaseType> tables)
有主叫方不要求有实例的类。为了使用该类型而实例化它似乎很浪费。 – rediVider 2010-08-13 21:04:33
我不知道我明白。如果您将IList传递给某个方法,那么我假设该列表的元素将实例化SomeType的类。我只是说,只要所有派生类型都继承自它,就可以使用BaseType作为IList的类型。 –
dcp
2010-08-13 22:01:40
我没有得到对象列表。我收到了一个类型列表。 – rediVider 2010-10-07 23:57:45