44 lines
1.5 KiB
C#
44 lines
1.5 KiB
C#
|
|
using System.Reflection;
|
||
|
|
|
||
|
|
namespace Lesson21_特性练习
|
||
|
|
{
|
||
|
|
internal class Program
|
||
|
|
{
|
||
|
|
static void Main(string[] args)
|
||
|
|
{
|
||
|
|
Assembly assembly = Assembly.LoadFrom(@"D:\VisualStudio2022\VisualStudio Programe\C#\C#进阶\反射练习库\bin\Debug\反射练习库");
|
||
|
|
Type[] types = assembly.GetTypes();
|
||
|
|
for (int i = 0; i < types.Length; i++)
|
||
|
|
{
|
||
|
|
Console.WriteLine(types[i]);
|
||
|
|
}
|
||
|
|
//得type
|
||
|
|
Type playertype = assembly.GetType("反射练习库.Player");
|
||
|
|
//实例化对象
|
||
|
|
object playerObj = Activator.CreateInstance(playertype);
|
||
|
|
Console.WriteLine(playerObj);
|
||
|
|
|
||
|
|
FieldInfo[] fields = playertype.GetFields();
|
||
|
|
for (int i = 0; i < fields.Length; i++)
|
||
|
|
{
|
||
|
|
Console.WriteLine(fields[i]);
|
||
|
|
}
|
||
|
|
|
||
|
|
//首先得到自定义特性的Type
|
||
|
|
Type atrribute = assembly.GetType("反射练习库.MyCustomAttribute");
|
||
|
|
|
||
|
|
//赋值名字
|
||
|
|
FieldInfo fieldStr = playertype.GetField("name");
|
||
|
|
if(fieldStr.GetCustomAttribute(atrribute) != null)
|
||
|
|
{
|
||
|
|
Console.WriteLine("非法操作,随意修改name成员");
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
//检测是否被自定义特性修饰 如果是 就不能更改 而是提示
|
||
|
|
fieldStr.SetValue(playerObj, "123123");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|