<分区>
编辑:
当然,我的真实代码看起来并不完全像这样。我尝试编写半伪代码以使其更清楚我想做什么。
看起来它只是把事情搞砸了。
所以,我真正想做的是:
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!
}
原帖:
嗨!
我正在尝试遍历命名空间中的所有接口(interface),并将它们作为参数发送给这样的通用方法:
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’类型的操作数” 关于如何解决这个问题的任何想法?