反射调用方法可以用在架构只用
先写好结口
接口具体实现在后面的状况
对特定使用的方法可以标记特别属性
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Reflection;
namespace ReflectMethod
{
//自定义特性类
[AttributeUsage(AttributeTargets.All)]
class GameSystem : Attribute//正常格式是GameSystemAttribute这样的
{
public GameSystem() { }
}
//自定义一个player类
class player
{
//GameSystem特性类的名字,如果定义的时候特性类的名字是这样GameSystemAttribute打上特性也是一样的
[GameSystem]//给start打上特性
public void start()
{
Console.WriteLine("GameSystem start");
}
public void Updata()
{
Console.WriteLine("my updata");
}
}
class Program
{
static void Main(string[] args)
{
//获取命名空间的所有类型
Type[] types = typeof(Program).Assembly.GetTypes();
foreach (Type t in types)
{
AttributeLogic(t);
}
Console.ReadKey();
}
static void AttributeLogic(Type type)
{
//获取类中的方法
foreach (MethodInfo method in type.GetMethods())
{
//获取方法的属性
foreach (Attribute attr in method.GetCustomAttributes())
{
//判断是不是制定的属性
if (attr is GameSystem)
{
//实例化类
object reflectTest = Activator.CreateInstance(type);
//从类中获取方法
MethodInfo methodInfo = type.GetMethod(method.Name);
//执行方法
methodInfo.Invoke(reflectTest, null);
}
}
}
}
}
}