通过反射在 class 上调用多个通用接口方法
Invoke multiple generic interface methods on a class through reflection
警告: 虽然接受的答案是正确的,但对于任何试图实施此问题的人,请参阅@CodesInChaos 的评论也是如此。这对我来说是个坏主意。
我有一个通用接口和一个实现接口 'n' 次的 class:
interface IA<T>
{
T Foo();
}
class Baz1 { }
class Baz2 { }
class Bar : IA<Baz1>, IA<Baz2>
{
Baz1 Foo() { return new Baz1(); }
Baz2 Foo() { return new Baz2(); }
}
如何使用反射在 Bar
的实例上调用两个 Foo
方法?
我已经有以下代码来获取接口定义和泛型类型参数:
class Frobber
{
void Frob(object frobbee)
{
var interfaces = frobbee.GetType()
.GetInterfaces()
.Where(i => i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IA<>).GetGenericTypeDefinition());
}
}
定义:
interface IA<T>
{
T Foo();
}
class Baz1 { }
class Baz2 { }
class Bar : IA<Baz1>, IA<Baz2>
{
Baz2 IA<Baz2>.Foo()
{
return new Baz2();
}
Baz1 IA<Baz1>.Foo()
{
return new Baz1();
}
}
代码:
Bar b = new Bar();
var methods = typeof(Bar).GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IA<>)).Select(i => i.GetMethod("Foo"));
foreach(var method in methods)
{
var invoked = method.Invoke(b, null); // or add params instead of null when needed
}
警告: 虽然接受的答案是正确的,但对于任何试图实施此问题的人,请参阅@CodesInChaos 的评论也是如此。这对我来说是个坏主意。
我有一个通用接口和一个实现接口 'n' 次的 class:
interface IA<T>
{
T Foo();
}
class Baz1 { }
class Baz2 { }
class Bar : IA<Baz1>, IA<Baz2>
{
Baz1 Foo() { return new Baz1(); }
Baz2 Foo() { return new Baz2(); }
}
如何使用反射在 Bar
的实例上调用两个 Foo
方法?
我已经有以下代码来获取接口定义和泛型类型参数:
class Frobber
{
void Frob(object frobbee)
{
var interfaces = frobbee.GetType()
.GetInterfaces()
.Where(i => i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IA<>).GetGenericTypeDefinition());
}
}
定义:
interface IA<T>
{
T Foo();
}
class Baz1 { }
class Baz2 { }
class Bar : IA<Baz1>, IA<Baz2>
{
Baz2 IA<Baz2>.Foo()
{
return new Baz2();
}
Baz1 IA<Baz1>.Foo()
{
return new Baz1();
}
}
代码:
Bar b = new Bar();
var methods = typeof(Bar).GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IA<>)).Select(i => i.GetMethod("Foo"));
foreach(var method in methods)
{
var invoked = method.Invoke(b, null); // or add params instead of null when needed
}