我的程序集中有以下界面
IGenericInterface<T1, T2>
和一些实施此界面的人员
class FirstClass : IGenericInterface<Cat, Dog>
class SecondClass : IGenericInterface<Horse, Cow>
我需要使用反射
来写这样的东西for each class that implements IGeiericInterface<,>
Console.WriteLine("Class {0} implements with {1}, {2}")
,输出应为
Class FirstClass implements with Cat, Dog
Class SecondClass implements with Horse, Cow
答案 0 :(得分:0)
试试这个:
var assembly = Assembly.GetExecutingAssembly(); //or whatever else
var types =
from t in assembly.GetTypes()
from i in t.GetInterfaces()
where i.IsGenericType && i.GetGenericTypeDefinition().Equals(typeof(IFoo<,>))
select new
{
Type = t,
Args = i.GetGenericArguments().ToList()
};
foreach (var item in types)
{
Console.WriteLine("Class {0} implements with {1}, {2}", item.Type.Name, item.Args[0].Name, item.Args[1].Name);
}
更新: 根据评论者的要求,对代码的作用进行一些总结。