通过反射获取实现同一接口的所有类
Posted wt-li
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过反射获取实现同一接口的所有类相关的知识,希望对你有一定的参考价值。
var assemblies = new List<Assembly>() { typeof(OEAppHost).Assembly };
var types = assemblies.SelectMany(x => x.GetTypes())
.Where(x => (x.GetInterfaces().Contains(typeof(ICheckOrder))))
.ToArray();
var checkOrderInstances = types.Select(x => x.CreateInstance()).ToList();
void RunNeedCheckProcess(object instance)
{
try
{
if (instance is ICheckOrder checkOrder)
checkOrder.Execute();
}
catch (Exception)
{
}
}
checkOrderInstances.ForEach(RunNeedCheckProcess);
static class ReflectExtension
{
public static bool HasInterface(this Type type, Type interfaceType)
{
foreach (var t in type.GetInterfaces())
{
if (t == interfaceType)
return true;
}
return false;
}
}
public interface ICheckOrder
{
void Execute();
}
public class CheckOrderName : ICheckOrder
{
public void Execute()
{
//throw new NotImplementedException();
}
}
以上是关于通过反射获取实现同一接口的所有类的主要内容,如果未能解决你的问题,请参考以下文章