转载链接:https://blog.csdn.net/Eat_ones_word/article/details/86535457
/// <summary>
///先定义需要被继承的 接口/类
/// </summary>
public interface IHumanGeneral
{
/// <summary>
/// 调用接口需要实现的方法
/// </summary>
void Execute();
}
/// <summary>
/// 实现接口的类
/// </summary>
class TeseClass : IHumanGeneral
{
public void Execute()
{
Console.WriteLine(" -- 成功!");
return;
}
}
/// <summary>
/// 反射实现方法
/// </summary>
public static void ReflexFunction()
{
#region -- 查找所有实现当前接口的类
//获取 IHumanGeneral 接口的接口类型
Type t_1 = typeof(IHumanGeneral);
//获取所有实现IHumanGeneral接口的类的类型
Type[] types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t1 => t1.GetInterfaces().Contains(t_1))).ToArray();
//遍历获取到的类的集合
foreach (var v in types)
{
Console.WriteLine("类名:"+v.Name);
//获取当前类的类名
var ClassName=v.Name;
//获取当前类下的所有公共方法
var FunctionS = v.GetMethods();
//遍历获取到的公共方法
foreach (var Functions in FunctionS)
{
//判断当前方法名称是否等于Execute
if (Functions.Name=="Execute")
{
//根据当前类的类型来创建一个object类型的类的实例
var new_class1 = Activator.CreateInstance(v);
//无参方法的调用示例
Functions.Invoke(new_class1, null);
//含参方法的调用示例
//Functions.Invoke(new_class1, new object[] {"参数值1","参数值2","参数值3" });
}
}
}
#endregion
}