Type
// typeof
Type type = typeof(MyClass);
// GetType
MyClass obj = new MyClass();
Type type = obj.GetType();基本信息
// 类型名称
string typeName = type.Name;
// 命名空间
string namespaceName = type.Namespace;
// 程序集
Assembly assembly = type.Assembly;属性、字段
获取
// 单个
PropertyInfo property = type.GetProperty("PropertyName");
FieldInfo field = type.GetField("FieldName");
// 多个
PropertyInfo[] properties = type.GetProperties(/* BindingFlags枚举 */);
FieldInfo[] fields = type.GetFields(/* BindingFlags枚举 */);读
需注意访问修饰符
// 属性
@PropertyInfo.GetValue(null); // 静态
@PropertyInfo.GetValue(实例对象); // 非静态
// 字段
@FieldInfo.GetValue(null); // 静态
@FieldInfo.GetValue(实例对象); // 非静态写
需注意访问修饰符
// 属性
@PropertyInfo.SetValue(null, Value); // 静态
@PropertyInfo.SetValue(实例对象, Value); //非静态
// 字段
@FieldInfo.SetValue(null, Value); // 静态
@FieldInfo.SetValue(实例对象, Value); // 非静态方法
获取
// 单个
MethodInfo[] method = type.GetMethods("MethodName");
// 多个
MethodInfo[] methods = type.GetMethods(/* BindingFlags枚举 */);调用
需注意访问修饰符
@MethodInfo.Invoke(null, null); // 静态、无参数
@MethodInfo.Invoke(实例对象, null); // 非静态、无参数
@MethodInfo.Invoke(null, new object[]{ 123, "123" }); // 静态、有参数
@MethodInfo.Invoke(实例对象, new object[]{ 123, "123" }); // 非静态、有参数创建实例
object instance = Activator.CreateInstance(type, new object[]{ 123, "123" });
// 无参数则传nullBindingFlags
- BindingFlags.Public
- BindingFlags.NonPublic
- BindingFlags.Static
- 等