为了账号安全,请及时绑定邮箱和手机立即绑定

使用仅在执行时知道的类型参数调用泛型方法

使用仅在执行时知道的类型参数调用泛型方法

C#
弑天下 2019-08-27 13:17:17
使用仅在执行时知道的类型参数调用泛型方法编辑:当然,我的真实代码看起来并不完全像这样。我试着编写半伪代码,以便更清楚地表达我想做的事情。看起来它只是把事情搞砸了。所以,我真正想做的是:Method<Interface1>();Method<Interface2>();Method<Interface3>();...嗯......我想也许我可以用反射把它变成一个循环。所以问题是:我该怎么做。我有很反射的浅识。所以代码示例会很棒。场景如下所示:public void Method<T>() where T : class{}public void AnotherMethod(){     Assembly assembly = Assembly.GetExecutingAssembly();     var interfaces = from i in assembly.GetTypes()     where i.Namespace == "MyNamespace.Interface" // only interfaces stored here     select i;     foreach(var i in interfaces)     {         Method<i>(); // Get compile error here!     }原帖:嗨!我正在尝试遍历命名空间中的所有接口,并将它们作为参数发送到这样的泛型方法:public void Method<T>() where T : class{}public void AnotherMethod(){     Assembly assembly = Assembly.GetExecutingAssembly();     var interfaces = from i in assembly.GetTypes()     where i.Namespace == "MyNamespace.Interface" // only interfaces stored here     select i;     foreach(var interface in interfaces)     {         Method<interface>(); // Get compile error here!     }}我得到的错误是“预期输入名称,但找到了本地变量名称”。如果我试试...     foreach(var interface in interfaces)     {         Method<interface.MakeGenericType()>(); // Still get compile error here!     }}我得到“不能将运算符'<'应用于'方法组'和'System.Type'类型的操作数”“如何解决这个问题?
查看完整描述

2 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

请注意,您可能会遇到“方法分辨率中的模糊匹配” GetMethod()。当您尝试获取的方法有一些重载时会发生这种情况。所以,你需要指定要使用你想要哪一个GetMethod("Name", new Type[] {arguments})

查看完整回答
反对 回复 2019-08-27
  • 2 回答
  • 0 关注
  • 459 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信