Unity中反射遍历命名空间的两种方法
// Unity中反射遍历命名空间的两种方法
// 1.
foreach (Type currType in GetType().Assembly.GetTypes())
{
Debug.Log(currType);
Debug.Log(currType.Namespace);
}
// 2. Assembly.GetAssembly() | Assembly.GetExecutingAssembly()
foreach (Type currType in Assembly.GetExecutingAssembly().GetTypes())
{
Debug.Log(currType);
Debug.Log(currType.Namespace);
}
使用:
private void DoScanner()
{
foreach (Type currType in GetType().Assembly.GetTypes())
{
// 扫描controller类
object[] objs = currType.GetCustomAttributes(typeof(ControllerAttribute), true);
foreach (object obj in objs)
{
ControllerAttribute attr = obj as ControllerAttribute;
object[] rms = currType.GetCustomAttributes(typeof(RequestMappingAttribute), true);
RequestMappingAttribute requestMapping = rms[0] as RequestMappingAttribute;
//Debug.Log("Class RequestMapping:"+requestMapping.Value);
if (null != attr)
{
Debug.Log(currType);
//取方法上的自定义特性
foreach (MethodInfo method in currType.GetMethods())
{
object[] objAttrs = method.GetCustomAttributes(typeof(RequestMappingAttribute), true);
if (objAttrs.Length > 0)
{
foreach (object objAttr in objAttrs)
{
RequestMappingAttribute rm = objAttr as RequestMappingAttribute;
//Debug.Log("方法上的Key值:" + attr.Key);
Debug.Log("RequestMapping:" + requestMapping.Value + rm.Value);
commandDic.Add(requestMapping.Value + rm.Value,
new MethodModel() {
Key = requestMapping.Value + rm.Value,
MethodName = method.Name,
Obj = obj,
Method = method,
ParameterInfos = method.GetParameters(),
ReturnParameter = method.ReturnParameter
});
}
}
}
}
}
}
}