using System;
using System.Reflection;
using UnityEngine;
using Object = System.Object;
namespace MyAttr
{
public class MyTypeClass
{
public void Test01()
{
Debug.Log("Test01 ");
}
public int Test02()
{
Debug.Log("Test02 ");
return 2;
}
public int Test03(int num)
{
Debug.Log("Test03 ");
return num;
}
protected static int Test04(int num)
{
Debug.Log("Test04 ");
return num;
}
}
public class Legend : Attribute
{
public string Name;
public string SkillName;
public Legend(string name, string skillName)
{
Name = name;
SkillName = skillName;
}
}
[Legend("金克斯", "超究极死神飞弹")]
public class Jinx
{
}
public class MyAttributeTest : MonoBehaviour
{
private void Start()
{
//测试反射调用方法
TestRefMethod();
//测试自定义特性
TestCustomAttribute();
}
//测试反射调用方法
private void TestRefMethod()
{
Object obj = new MyTypeClass();
Type myTypeClass = typeof(MyTypeClass);
MethodInfo[] methods = myTypeClass.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic |BindingFlags.Static | BindingFlags.DeclaredOnly);
Debug.Log("methods length " + methods.Length);
int num = 1;
Object numObj = null;
foreach (var method in methods)
{
ParameterInfo[] parameterInfos = method.GetParameters();
if (parameterInfos.Length > 0)
{
if (method.IsStatic)
//静态方法不用传入对象,直接通过类调用对应的方法
num = (int)method.Invoke(null, new Object[]{4});
else
num = (int)method.Invoke(obj, new Object[]{3});
}
else
{
//非静态方法必须传入对象
numObj = method.Invoke(obj, null);
if (numObj != null)
num = (int) numObj;
}
Debug.Log("num " + num);
}
}
//测试自定义特性
private void TestCustomAttribute()
{
Type jinx = typeof(Jinx);
Attribute[] attributes = Attribute.GetCustomAttributes(jinx);
foreach (var attribute in attributes)
{
if (attribute is Legend)
{
Legend j = (Legend) attribute;
Debug.Log("Name " + j.Name + " SkillName " + j.SkillName);
}
}
}
}
}
输出:
4
Test01
1
Test02
2
Test03
3
Test04
4