有没有办法将未知数量的类型传递给 C# 中的泛型方法?
我有一种方法
void InitAndLoadTables(DbConnection cnctn, Dictionary<string, DbTableLoadParameters> tableNamesAndParameters)
,字典可以有任意数量的表。每个表对应一个类。
当我迭代所有表时,我想
public void Init<T>(string tableName)
为所有表调用通用方法。我尝试将类的类型包含为 DbTableLoadParameters 的属性,
Type ObjectType { get; set; }
并在调用 Init 时使用它。这是行不通的。那么有可能做到吗?如果表的数量是固定的,我也许可以使 InitAndLoadTables 变得通用,
InitAndLoadTables<T, K, V>
但事实并非如此。所以只能在其他地方调用 Init,比如
Init<Orders>("Orders");
Thanks & BR-马蒂
I have a method
void InitAndLoadTables(DbConnection cnctn, Dictionary<string, DbTableLoadParameters> tableNamesAndParameters)
where dictionary can have any amount of tables. Every table corresponds a class.
When I iterate through all the tables I would like to call generic method
public void Init<T>(string tableName)
for all the tables. I tried to include type of the class to be property of DbTableLoadParameters as
Type ObjectType { get; set; }
and use that when calling Init. This does not work. So is it even possible to do? If the amount of tables would be fixed I could maybe make InitAndLoadTables generic like
InitAndLoadTables<T, K, V>
but it isn't. So is only possibility to call Init elsewhere like
Init<Orders>("Orders");
Thanks & BR -Matti
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无法将任意数量的类型参数传递给泛型方法,因为泛型方法始终具有固定数量的类型参数。
然而,你似乎根本不需要这个。有一种方法可以调用运行时已知类型的泛型方法,但这涉及反射,这听起来像是您真正想要的:
输出:
There is no way to pass an arbitrary number of type arguments to a generic method, because a generic method always has a fixed number of type arguments.
However, you don't even seem to need that. There is a way to call a generic method with a runtime-known type, but this involves reflection, which sounds like it's what you're really after:
Output: