Type

CS
// typeof
Type type = typeof(MyClass);
// GetType
MyClass obj = new MyClass();
Type type = obj.GetType();
点击展开查看更多

基本信息

CS
// 类型名称
string typeName = type.Name;
// 命名空间
string namespaceName = type.Namespace;
// 程序集
Assembly assembly = type.Assembly;
点击展开查看更多

属性、字段

获取

CS
// 单个
PropertyInfo property = type.GetProperty("PropertyName");
FieldInfo field = type.GetField("FieldName");
// 多个
PropertyInfo[] properties = type.GetProperties(/* BindingFlags枚举 */);
FieldInfo[] fields = type.GetFields(/* BindingFlags枚举 */);
点击展开查看更多

需注意访问修饰符

CS
// 属性
@PropertyInfo.GetValue(null);    // 静态
@PropertyInfo.GetValue(实例对象); // 非静态
// 字段
@FieldInfo.GetValue(null);       // 静态
@FieldInfo.GetValue(实例对象);    // 非静态
点击展开查看更多

需注意访问修饰符

CS
// 属性
@PropertyInfo.SetValue(null, Value);    // 静态
@PropertyInfo.SetValue(实例对象, Value); //非静态
// 字段
@FieldInfo.SetValue(null, Value);    // 静态
@FieldInfo.SetValue(实例对象, Value); // 非静态
点击展开查看更多

方法

获取

CS
// 单个
MethodInfo[] method = type.GetMethods("MethodName");
// 多个
MethodInfo[] methods = type.GetMethods(/* BindingFlags枚举 */);
点击展开查看更多

调用

需注意访问修饰符

CS
@MethodInfo.Invoke(null, null); // 静态、无参数
@MethodInfo.Invoke(实例对象, null); // 非静态、无参数
@MethodInfo.Invoke(null, new object[]{ 123, "123" }); // 静态、有参数
@MethodInfo.Invoke(实例对象, new object[]{ 123, "123" }); // 非静态、有参数
点击展开查看更多

创建实例

CS
object instance = Activator.CreateInstance(type, new object[]{ 123, "123" });
// 无参数则传null
点击展开查看更多

BindingFlags

版权声明

作者: Chaim

链接: https://chaim.eu.org/posts/%E7%B1%BB%E5%9E%8B-type/

许可证: CC BY-NC-SA 4.0

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Please attribute the source, use non-commercially, and maintain the same license.

开始搜索

输入关键词搜索文章内容

↑↓
ESC
⌘K 快捷键