using System;
using System.Reflection;
// 测试类
public class Person
{
// 公共字段
public string Name;
// 私有字段
private int _age;
// 公共属性
public int Age
{
get => _age;
set { if (value > 0) _age = value; }
}
// 无参构造函数
public Person()
{
Name = "未知";
_age = 0;
}
// 有参构造函数
public Person(string name, int age)
{
Name = name;
_age = age;
}
// 公共方法
public string SayHello()
{
return $"你好,我是{Name},今年{_age}岁!";
}
// 私有方法
private string GetSecret()
{
return $"我的秘密:{Name}的年龄是{_age}";
}
}
csharp复制代码
2).获取Type对象(反射的入口)
Type是反射的核心, 获取它有3种常用方式
// 方式1:通过typeof关键字(无需实例)
Type type1 = typeof(Person);
// 方式2:通过对象实例的GetType()方法
Person p = new Person();
Type type2 = p.GetType();
// 方式3:通过类型全名(适用于动态加载场景)
Type type3 = Type.GetType("Person"); // 简单场景,复杂场景需指定程序集名称
// 输出类型基础信息
Console.WriteLine($"类型名称:{type1.Name}");
Console.WriteLine($"是否是类:{type1.IsClass}");