【超详细】C#自定义工具类-ReflectionHelper反射助手类

目录

ReflectionHelper反射助手类

1.主要功能  

1.1.常量相关  

1.2.嵌套类相关  

1.3.属性与字段相关 

1.4.方法相关

1.5.实例创建相关

1.6.特性相关

1.7.程序集相关

2.完整代码

3.测试

4.总结


      本篇文章来分享一下反射助手类,ReflectionHelper封装了C#反射核心操作。了解反射可以参考【一文了解】C#反射

ReflectionHelper反射助手类

1.主要功能  

1.1.常量相关  

1)核心功能:提取类中公共静态常量(支持指定类型,如字符串或任意类型),区分const常量与readonly字段,支持跨基类查找(通过FlattenHierarchy)。  

2)典型用途:读取配置类中的常量(如系统参数、枚举映射值)。  

●GetConstStringValues<T>():获取指定类型T中所有公共静态字符串常量的值  

●GetConstStringValues(Type type):获取指定类型type中所有公共静态字符串常量的值  

●GetConstValues<T, TValue>():获取指定类型T中所有指定类型TValue的公共静态常量(返回字段名与值的字典)  

●GetConstValues<TValue>(Type type):获取指定类型type中所有指定类型TValue的公共静态常量(返回字段名与值的字典)  

/// <summary>
/// 获取类中所有公共静态常量字段的值(支持字符串类型)
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <returns>常量值列表(原方法返回字段名,此处修正为返回值)</returns>
public static List<string> GetConstStringValues<T>()
{
    return GetConstStringValues(typeof(T));
}
/// <summary>
/// 获取类中所有公共静态常量字段的值(支持字符串类型)
/// </summary>
/// <param name="type">目标类型</param>
/// <returns>常量值列表</returns>
public static List<string> GetConstStringValues(Type type)
{
    //BindingFlags.FlattenHierarchy:不仅查找当前类型本身声明的成员,还会递归查找其所有基类(父类、祖父类等)中声明的公共静态成员
    //与 DeclaredOnly 互斥:DeclaredOnly 表示 “仅查找当前类型自身声明的成员,不包含基类”,而 FlattenHierarchy 是 “包含基类的公共静态成员”,二者不能同时使用(逻辑冲突)。
    return type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
                //用于精准获取 “字符串类型的常量字段”
                //field.IsLiteral:判断字段是否是 const 常量。field.IsInitOnly:判断字段是否为 readonly 字段
                .Where(field => field.IsLiteral && !field.IsInitOnly && field.FieldType == typeof(string))
                .Select(field => field.GetValue(null) as string)
                .Where(value => value != null)
                .ToList();
}
/// <summary>
/// 获取类中所有公共静态常量(支持任意类型)
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <typeparam name="TValue">常量值类型</typeparam>
/// <returns>常量名与值的字典</returns>
public static Dictionary<string, TValue> GetConstValues<T, TValue>()
{
    return GetConstValues<TValue>(typeof(T));
}
/// <summary>
/// 获取类中所有公共静态常量(支持任意类型)
/// </summary>
/// <param name="type">目标类型</param>
/// <typeparam name="TValue">常量值类型</typeparam>
/// <returns>常量名与值的字典</returns>
public static Dictionary<string, TValue> GetConstValues<TValue>(Type type)
{
    return type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
                .Where(field => field.IsLiteral && !field.IsInitOnly && field.FieldType == typeof(TValue))
                .ToDictionary(
                    field => field.Name,
                    field => (TValue)field.GetValue(null)
                );
}

1.2.嵌套类相关  

1)核心功能:获取外部类中的嵌套类(支持按访问级别筛选),以及嵌套类中的公共静态字段。  

2)典型用途:解析包含嵌套结构的复杂类型(如工具类中的内部辅助类)。  

●GetNestedClasses<T>(BindingFlags bindingFlags):获取外部类T中符合指定访问级别的嵌套类 

●GetNestedClassFields<TOuter>():获取外部类TOuter中所有公共嵌套类的公共静态字段(返回嵌套类类型与字段列表的字典)  

/// <summary>
/// 获取类中所有嵌套类(支持筛选访问级别)
/// </summary>
/// <typeparam name="T">外部类类型</typeparam>
/// <param name="bindingFlags">筛选条件(如 Public/NonPublic)</param>
/// <returns>嵌套类类型数组</returns>
public static Type[] GetNestedClasses<T>(BindingFlags bindingFlags)
{
    return typeof(T).GetNestedTypes(bindingFlags);
}
/// <summary>
/// 获取嵌套类中符合条件的公共静态字段
/// </summary>
/// <typeparam name="TOuter">外部类类型</typeparam>
/// <returns>嵌套类字段信息</returns>
public static Dictionary<Type, List<FieldInfo>> GetNestedClassFields<TOuter>()
{
    var nestedTypes = typeof(TOuter).GetNestedTypes(BindingFlags.Public);
    return nestedTypes.ToDictionary(
        type => type,
        type => type.GetFields(BindingFlags.Public | BindingFlags.Static).ToList()
    );
}

1.3.属性与字段相关 

1)核心功能:读取类的属性/字段信息及值,支持公共/私有成员,可动态设置公共属性值。  

2)典型用途:对象序列化(遍历属性值)、访问私有成员(如单元测试白盒验证)。  

●GetPublicProperties<T>():获取指定类型T中所有公共属性(含实例和静态)  

●GetPublicProperties(Type type):获取指定类型type中所有公共属性(含实例和静态)  

●GetPublicPropertyValues(object obj):获取对象obj的所有公共实例属性值(返回属性名与值的字典)  

●SetPublicPropertyValue(object obj, string propertyName, object value):设置对象obj的指定公共实例属性值(返回设置是否成功)  

●GetPrivateFields<T>():获取指定类型T中所有私有实例字段  

●GetPrivateFieldValue(object obj, string fieldName):获取对象obj的指定私有实例字段值  

/// <summary>
/// 获取类中所有公共属性(含实例和静态)
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <returns>属性信息列表</returns>
public static List<PropertyInfo> GetPublicProperties<T>()
{
    return GetPublicProperties(typeof(T));
}
/// <summary>
/// 获取类中所有公共属性(含实例和静态)
/// </summary>
/// <param name="type">目标类型</param>
/// <returns>属性信息列表</returns>
public static List<PropertyInfo> GetPublicProperties(Type type)
{
    return type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).ToList();
}
/// <summary>
/// 获取对象的所有公共属性值
/// </summary>
/// <param name="obj">目标对象</param>
/// <returns>属性名与值的字典</returns>
public static Dictionary<string, object> GetPublicPropertyValues(object obj)
{
    if (obj == null) return new Dictionary<string, object>();
    Type type = obj.GetType();
    return type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .ToDictionary(
                    prop => prop.Name,
                    prop => prop.GetValue(obj)
                );
}
/// <summary>
/// 设置对象的公共属性值
/// </summary>
/// <param name="obj">目标对象</param>
/// <param name="propertyName">属性名</param>
/// <param name="value">要设置的值</param>
/// <returns>是否设置成功</returns>
public static bool SetPublicPropertyValue(object obj, string propertyName, object value)
{
    if (obj == null || string.IsNullOrEmpty(propertyName)) return false;
    PropertyInfo prop = obj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
    if (prop == null || !prop.CanWrite) return false;
    prop.SetValue(obj, value);
    return true;
}
/// <summary>
/// 获取类中所有私有字段
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <returns>字段信息列表</returns>
public static List<FieldInfo> GetPrivateFields<T>()
{
    return typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList();
}
/// <summary>
/// 获取对象的私有字段值
/// </summary>
/// <param name="obj">目标对象</param>
/// <param name="fieldName">字段名</param>
/// <returns>字段值(获取失败返回 null)</returns>
public static object GetPrivateFieldValue(object obj, string fieldName)
{
    if (obj == null || string.IsNullOrEmpty(fieldName)) return null;
    FieldInfo field = obj.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
    return field?.GetValue(obj);
}

1.4.方法相关

1)核心功能:动态调用类的方法,支持公共/私有、实例/静态方法,适配带参数的重载方法。  

2)典型用途:插件系统中调用外部方法、触发私有逻辑(如框架回调)。  

●InvokePublicMethod(object obj, string methodName, params object[] parameters):调用对象obj的指定公共实例方法(返回方法返回值)  

●InvokePublicStaticMethod<T>(string methodName, params object[] parameters):调用类型T的指定公共静态方法(返回方法返回值)  

●InvokePublicStaticMethod(Type type, string methodName, params object[] parameters):调用指定类型type的指定公共静态方法(返回方法返回值)  

●InvokePrivateMethod(object obj, string methodName, params object[] parameters):调用对象obj的指定私有实例方法(返回方法返回值)  

/// <summary>
/// 调用对象的公共实例方法
/// </summary>
/// <param name="obj">目标对象</param>
/// <param name="methodName">方法名</param>
/// <param name="parameters">方法参数</param>
/// <returns>方法返回值</returns>
public static object InvokePublicMethod(object obj, string methodName, params object[] parameters)
{
    if (obj == null || string.IsNullOrEmpty(methodName)) return null;
    Type[] paramTypes = parameters?.Select(p => p?.GetType() ?? typeof(object)).ToArray();
    MethodInfo method = obj.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, null, paramTypes, null);
    return method?.Invoke(obj, parameters);
}
/// <summary>
/// 调用类的公共静态方法
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="methodName">方法名</param>
/// <param name="parameters">方法参数</param>
/// <returns>方法返回值</returns>
public static object InvokePublicStaticMethod<T>(string methodName, params object[] parameters)
{
    return InvokePublicStaticMethod(typeof(T), methodName, parameters);
}
/// <summary>
/// 调用类的公共静态方法
/// </summary>
/// <param name="type">目标类型</param>
/// <param name="methodName">方法名</param>
/// <param name="parameters">方法参数</param>
/// <returns>方法返回值</returns>
public static object InvokePublicStaticMethod(Type type, string methodName, params object[] parameters)
{
    if (type == null || string.IsNullOrEmpty(methodName)) return null;
    Type[] paramTypes = parameters?.Select(p => p?.GetType() ?? typeof(object)).ToArray();
    MethodInfo method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static, null, paramTypes, null);
    return method?.Invoke(null, parameters);
}
public static object InvokePrivateMethod(object obj, string methodName, params object[] parameters)
{
    if (obj == null || string.IsNullOrEmpty(methodName)) return null;
    Type[] paramTypes = parameters?.Select(p => p?.GetType() ?? typeof(object)).ToArray();
    MethodInfo method = obj.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, paramTypes, null);
    return method?.Invoke(obj, parameters);
}

1.5.实例创建相关

1)核心功能:动态创建类型实例,支持无参/带参构造函数,以及泛型类型实例化。  

2)典型用途:依赖注入(DI)中动态创建服务实例、工厂模式生成对象。  

●CreateInstance(Type type):通过无参构造函数创建指定类型type的实例(失败返回null)  

●CreateInstance(Type type, params object[] parameters):通过带参数的构造函数创建指定类型type的实例(失败返回null)  

●CreateGenericInstance(Type genericType, params Type[] typeArguments):创建泛型类型实例(如List<string>,需传入泛型定义和参数类型)  

/// <summary>
/// 动态创建类型实例(调用无参构造函数)
/// </summary>
/// <param name="type">目标类型</param>
/// <returns>创建的实例(失败返回 null)</returns>
public static object CreateInstance(Type type)
{
    try
    {
        return Activator.CreateInstance(type);
    }
    catch
    {
        return null;//构造函数不存在或私有等情况
    }
}
/// <summary>
/// 动态创建类型实例(调用带参数的构造函数)
/// </summary>
/// <param name="type">目标类型</param>
/// <param name="parameters">构造函数参数</param>
/// <returns>创建的实例(失败返回 null)</returns>
public static object CreateInstance(Type type, params object[] parameters)
{
    try
    {
        return Activator.CreateInstance(type, parameters);
    }
    catch
    {
        return null;
    }
}
/// <summary>
/// 动态创建泛型类型实例(如 List<string>)
/// </summary>
/// <param name="genericType">泛型类型(如 typeof(List<>))</param>
/// <param name="typeArguments">泛型参数类型(如 typeof(string))</param>
/// <returns>创建的实例</returns>
public static object CreateGenericInstance(Type genericType, params Type[] typeArguments)
{
    if (!genericType.IsGenericTypeDefinition) return null;
    Type constructedType = genericType.MakeGenericType(typeArguments);
    return CreateInstance(constructedType);
}

1.6.特性相关

1)核心功能:读取类型或属性上的自定义特性,支持继承链查找。  

2)典型用途:解析数据校验特性(如[Required])、业务标记特性(如[Description])。  

●GetTypeAttribute<TAttribute, T>(bool inherit = false):获取指定类型T上的指定特性TAttribute(支持搜索继承链)  

●GetTypeAttribute<TAttribute>(Type type, bool inherit = false):获取指定类型type上的指定特性TAttribute(支持搜索继承链)  

●GetPropertyAttribute<TAttribute>(object obj, string propertyName):获取对象obj的指定属性上的指定特性TAttribute  

/// <summary>
/// 获取类型上的指定特性
/// </summary>
/// <typeparam name="TAttribute">特性类型</typeparam>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="inherit">是否搜索继承链</param>
/// <returns>特性实例(不存在返回 null)</returns>
public static TAttribute GetTypeAttribute<TAttribute, T>(bool inherit = false) where TAttribute : Attribute
{
    return GetTypeAttribute<TAttribute>(typeof(T), inherit);
}
/// <summary>
/// 获取类型上的指定特性
/// </summary>
/// <typeparam name="TAttribute">特性类型</typeparam>
/// <param name="type">目标类型</param>
/// <param name="inherit">是否搜索继承链</param>
/// <returns>特性实例(不存在返回 null)</returns>
public static TAttribute GetTypeAttribute<TAttribute>(Type type, bool inherit = false) where TAttribute : Attribute
{
    return Attribute.GetCustomAttribute(type, typeof(TAttribute), inherit) as TAttribute;
}
/// <summary>
/// 获取属性上的指定特性
/// </summary>
/// <typeparam name="TAttribute">特性类型</typeparam>
/// <param name="obj">目标对象</param>
/// <param name="propertyName">属性名</param>
/// <returns>特性实例(不存在返回 null)</returns>
public static TAttribute GetPropertyAttribute<TAttribute>(object obj, string propertyName) where TAttribute : Attribute
{
    if (obj == null || string.IsNullOrEmpty(propertyName)) return null;
    PropertyInfo prop = obj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
    return prop?.GetCustomAttribute<TAttribute>();
}

1.7.程序集相关

1)核心功能:从程序集中查找接口实现类,加载外部程序集并获取类型。  

2)典型用途:插件系统(扫描并加载插件实现)、模块化开发(动态加载外部模块类型)。  

●GetInterfaceImplementations<TInterface>(Assembly assembly):从指定程序集assembly中获取指定接口TInterface的所有非抽象实现类  

●LoadTypeFromAssembly(string assemblyPath, string typeFullName):从指定路径的程序集中加载指定全名的类型(失败返回null)

/// <summary>
/// 从程序集中获取所有指定接口的实现类
/// </summary>
/// <typeparam name="TInterface">接口类型</typeparam>
/// <param name="assembly">目标程序集</param>
/// <returns>实现类类型列表</returns>
public static List<Type> GetInterfaceImplementations<TInterface>(Assembly assembly)
{
    Type interfaceType = typeof(TInterface);
    if (!interfaceType.IsInterface) return new List<Type>();
    //获取实现了指定接口的非抽象类
    //interfaceType.IsAssignableFrom(type):判断type是否“可赋值给 interfaceType”,即type是否实现了interfaceType接口,或type本身就是interfaceType接口类型
    //type.IsClass:判断 type 是否为类类型(class)
    //type.IsAbstract:判断 type 是否为抽象类
    return assembly.GetTypes()
                    .Where(type => interfaceType.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)
                    .ToList();
}
/// <summary>
/// 加载程序集并获取类型
/// </summary>
/// <param name="assemblyPath">程序集路径(.dll 或 .exe)</param>
/// <param name="typeFullName">类型全名(含命名空间,嵌套类型用+连接,如 Namespace.OuterClass+InnerClass)</param>
/// <returns>类型(失败返回 null)</returns>
public static Type LoadTypeFromAssembly(string assemblyPath, string typeFullName)
{
    try
    {
        Assembly assembly = Assembly.LoadFrom(assemblyPath);
        return assembly.GetType(typeFullName);
    }
    catch
    {
        return null;
    }
}

2.完整代码

public static class ReflectionHelper
{
    #region 常量相关
    /// <summary>
    /// 获取类中所有公共静态常量字段的值(支持字符串类型)
    /// </summary>
    /// <typeparam name="T">目标类型</typeparam>
    /// <returns>常量值列表(原方法返回字段名,此处修正为返回值)</returns>
    public static List<string> GetConstStringValues<T>()
    {
        return GetConstStringValues(typeof(T));
    }
    /// <summary>
    /// 获取类中所有公共静态常量字段的值(支持字符串类型)
    /// </summary>
    /// <param name="type">目标类型</param>
    /// <returns>常量值列表</returns>
    public static List<string> GetConstStringValues(Type type)
    {
        //BindingFlags.FlattenHierarchy:不仅查找当前类型本身声明的成员,还会递归查找其所有基类(父类、祖父类等)中声明的公共静态成员
        //与 DeclaredOnly 互斥:DeclaredOnly 表示 “仅查找当前类型自身声明的成员,不包含基类”,而 FlattenHierarchy 是 “包含基类的公共静态成员”,二者不能同时使用(逻辑冲突)。
        return type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
                   //用于精准获取 “字符串类型的常量字段”
                   //field.IsLiteral:判断字段是否是 const 常量。field.IsInitOnly:判断字段是否为 readonly 字段
                   .Where(field => field.IsLiteral && !field.IsInitOnly && field.FieldType == typeof(string))
                   .Select(field => field.GetValue(null) as string)
                   .Where(value => value != null)
                   .ToList();
    }
    /// <summary>
    /// 获取类中所有公共静态常量(支持任意类型)
    /// </summary>
    /// <typeparam name="T">目标类型</typeparam>
    /// <typeparam name="TValue">常量值类型</typeparam>
    /// <returns>常量名与值的字典</returns>
    public static Dictionary<string, TValue> GetConstValues<T, TValue>()
    {
        return GetConstValues<TValue>(typeof(T));
    }
    /// <summary>
    /// 获取类中所有公共静态常量(支持任意类型)
    /// </summary>
    /// <param name="type">目标类型</param>
    /// <typeparam name="TValue">常量值类型</typeparam>
    /// <returns>常量名与值的字典</returns>
    public static Dictionary<string, TValue> GetConstValues<TValue>(Type type)
    {
        return type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
                   .Where(field => field.IsLiteral && !field.IsInitOnly && field.FieldType == typeof(TValue))
                   .ToDictionary(
                       field => field.Name,
                       field => (TValue)field.GetValue(null)
                   );
    }
    #endregion


    #region 嵌套类相关
    /// <summary>
    /// 获取类中所有嵌套类(支持筛选访问级别)
    /// </summary>
    /// <typeparam name="T">外部类类型</typeparam>
    /// <param name="bindingFlags">筛选条件(如 Public/NonPublic)</param>
    /// <returns>嵌套类类型数组</returns>
    public static Type[] GetNestedClasses<T>(BindingFlags bindingFlags)
    {
        return typeof(T).GetNestedTypes(bindingFlags);
    }
    /// <summary>
    /// 获取嵌套类中符合条件的公共静态字段
    /// </summary>
    /// <typeparam name="TOuter">外部类类型</typeparam>
    /// <returns>嵌套类字段信息</returns>
    public static Dictionary<Type, List<FieldInfo>> GetNestedClassFields<TOuter>()
    {
        var nestedTypes = typeof(TOuter).GetNestedTypes(BindingFlags.Public);
        return nestedTypes.ToDictionary(
            type => type,
            type => type.GetFields(BindingFlags.Public | BindingFlags.Static).ToList()
        );
    }
    #endregion

    #region 属性与字段相关
    /// <summary>
    /// 获取类中所有公共属性(含实例和静态)
    /// </summary>
    /// <typeparam name="T">目标类型</typeparam>
    /// <returns>属性信息列表</returns>
    public static List<PropertyInfo> GetPublicProperties<T>()
    {
        return GetPublicProperties(typeof(T));
    }
    /// <summary>
    /// 获取类中所有公共属性(含实例和静态)
    /// </summary>
    /// <param name="type">目标类型</param>
    /// <returns>属性信息列表</returns>
    public static List<PropertyInfo> GetPublicProperties(Type type)
    {
        return type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).ToList();
    }
    /// <summary>
    /// 获取对象的所有公共属性值
    /// </summary>
    /// <param name="obj">目标对象</param>
    /// <returns>属性名与值的字典</returns>
    public static Dictionary<string, object> GetPublicPropertyValues(object obj)
    {
        if (obj == null) return new Dictionary<string, object>();
        Type type = obj.GetType();
        return type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    .ToDictionary(
                        prop => prop.Name,
                        prop => prop.GetValue(obj)
                    );
    }
    /// <summary>
    /// 设置对象的公共属性值
    /// </summary>
    /// <param name="obj">目标对象</param>
    /// <param name="propertyName">属性名</param>
    /// <param name="value">要设置的值</param>
    /// <returns>是否设置成功</returns>
    public static bool SetPublicPropertyValue(object obj, string propertyName, object value)
    {
        if (obj == null || string.IsNullOrEmpty(propertyName)) return false;
        PropertyInfo prop = obj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
        if (prop == null || !prop.CanWrite) return false;
        prop.SetValue(obj, value);
        return true;
    }
    /// <summary>
    /// 获取类中所有私有字段
    /// </summary>
    /// <typeparam name="T">目标类型</typeparam>
    /// <returns>字段信息列表</returns>
    public static List<FieldInfo> GetPrivateFields<T>()
    {
        return typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList();
    }
    /// <summary>
    /// 获取对象的私有字段值
    /// </summary>
    /// <param name="obj">目标对象</param>
    /// <param name="fieldName">字段名</param>
    /// <returns>字段值(获取失败返回 null)</returns>
    public static object GetPrivateFieldValue(object obj, string fieldName)
    {
        if (obj == null || string.IsNullOrEmpty(fieldName)) return null;
        FieldInfo field = obj.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
        return field?.GetValue(obj);
    }
    #endregion

    #region 方法相关
    /// <summary>
    /// 调用对象的公共实例方法
    /// </summary>
    /// <param name="obj">目标对象</param>
    /// <param name="methodName">方法名</param>
    /// <param name="parameters">方法参数</param>
    /// <returns>方法返回值</returns>
    public static object InvokePublicMethod(object obj, string methodName, params object[] parameters)
    {
        if (obj == null || string.IsNullOrEmpty(methodName)) return null;
        Type[] paramTypes = parameters?.Select(p => p?.GetType() ?? typeof(object)).ToArray();
        MethodInfo method = obj.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, null, paramTypes, null);
        return method?.Invoke(obj, parameters);
    }
    /// <summary>
    /// 调用类的公共静态方法
    /// </summary>
    /// <typeparam name="T">目标类型</typeparam>
    /// <param name="methodName">方法名</param>
    /// <param name="parameters">方法参数</param>
    /// <returns>方法返回值</returns>
    public static object InvokePublicStaticMethod<T>(string methodName, params object[] parameters)
    {
        return InvokePublicStaticMethod(typeof(T), methodName, parameters);
    }
    /// <summary>
    /// 调用类的公共静态方法
    /// </summary>
    /// <param name="type">目标类型</param>
    /// <param name="methodName">方法名</param>
    /// <param name="parameters">方法参数</param>
    /// <returns>方法返回值</returns>
    public static object InvokePublicStaticMethod(Type type, string methodName, params object[] parameters)
    {
        if (type == null || string.IsNullOrEmpty(methodName)) return null;
        Type[] paramTypes = parameters?.Select(p => p?.GetType() ?? typeof(object)).ToArray();
        MethodInfo method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static, null, paramTypes, null);
        return method?.Invoke(null, parameters);
    }
    public static object InvokePrivateMethod(object obj, string methodName, params object[] parameters)
    {
        if (obj == null || string.IsNullOrEmpty(methodName)) return null;
        Type[] paramTypes = parameters?.Select(p => p?.GetType() ?? typeof(object)).ToArray();
        MethodInfo method = obj.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, paramTypes, null);
        return method?.Invoke(obj, parameters);
    }
    #endregion

    #region 实例创建相关
    /// <summary>
    /// 动态创建类型实例(调用无参构造函数)
    /// </summary>
    /// <param name="type">目标类型</param>
    /// <returns>创建的实例(失败返回 null)</returns>
    public static object CreateInstance(Type type)
    {
        try
        {
            return Activator.CreateInstance(type);
        }
        catch
        {
            return null;//构造函数不存在或私有等情况
        }
    }
    /// <summary>
    /// 动态创建类型实例(调用带参数的构造函数)
    /// </summary>
    /// <param name="type">目标类型</param>
    /// <param name="parameters">构造函数参数</param>
    /// <returns>创建的实例(失败返回 null)</returns>
    public static object CreateInstance(Type type, params object[] parameters)
    {
        try
        {
            return Activator.CreateInstance(type, parameters);
        }
        catch
        {
            return null;
        }
    }
    /// <summary>
    /// 动态创建泛型类型实例(如 List<string>)
    /// </summary>
    /// <param name="genericType">泛型类型(如 typeof(List<>))</param>
    /// <param name="typeArguments">泛型参数类型(如 typeof(string))</param>
    /// <returns>创建的实例</returns>
    public static object CreateGenericInstance(Type genericType, params Type[] typeArguments)
    {
        if (!genericType.IsGenericTypeDefinition) return null;
        Type constructedType = genericType.MakeGenericType(typeArguments);
        return CreateInstance(constructedType);
    }
    #endregion

    #region 特性相关
    /// <summary>
    /// 获取类型上的指定特性
    /// </summary>
    /// <typeparam name="TAttribute">特性类型</typeparam>
    /// <typeparam name="T">目标类型</typeparam>
    /// <param name="inherit">是否搜索继承链</param>
    /// <returns>特性实例(不存在返回 null)</returns>
    public static TAttribute GetTypeAttribute<TAttribute, T>(bool inherit = false) where TAttribute : Attribute
    {
        return GetTypeAttribute<TAttribute>(typeof(T), inherit);
    }
    /// <summary>
    /// 获取类型上的指定特性
    /// </summary>
    /// <typeparam name="TAttribute">特性类型</typeparam>
    /// <param name="type">目标类型</param>
    /// <param name="inherit">是否搜索继承链</param>
    /// <returns>特性实例(不存在返回 null)</returns>
    public static TAttribute GetTypeAttribute<TAttribute>(Type type, bool inherit = false) where TAttribute : Attribute
    {
        return Attribute.GetCustomAttribute(type, typeof(TAttribute), inherit) as TAttribute;
    }
    /// <summary>
    /// 获取属性上的指定特性
    /// </summary>
    /// <typeparam name="TAttribute">特性类型</typeparam>
    /// <param name="obj">目标对象</param>
    /// <param name="propertyName">属性名</param>
    /// <returns>特性实例(不存在返回 null)</returns>
    public static TAttribute GetPropertyAttribute<TAttribute>(object obj, string propertyName) where TAttribute : Attribute
    {
        if (obj == null || string.IsNullOrEmpty(propertyName)) return null;
        PropertyInfo prop = obj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
        return prop?.GetCustomAttribute<TAttribute>();
    }
    #endregion

    #region 程序集相关
    /// <summary>
    /// 从程序集中获取所有指定接口的实现类
    /// </summary>
    /// <typeparam name="TInterface">接口类型</typeparam>
    /// <param name="assembly">目标程序集</param>
    /// <returns>实现类类型列表</returns>
    public static List<Type> GetInterfaceImplementations<TInterface>(Assembly assembly)
    {
        Type interfaceType = typeof(TInterface);
        if (!interfaceType.IsInterface) return new List<Type>();
        //获取实现了指定接口的非抽象类
        //interfaceType.IsAssignableFrom(type):判断type是否“可赋值给 interfaceType”,即type是否实现了interfaceType接口,或type本身就是interfaceType接口类型
        //type.IsClass:判断 type 是否为类类型(class)
        //type.IsAbstract:判断 type 是否为抽象类
        return assembly.GetTypes()
                        .Where(type => interfaceType.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)
                        .ToList();
    }
    /// <summary>
    /// 加载程序集并获取类型
    /// </summary>
    /// <param name="assemblyPath">程序集路径(.dll 或 .exe)</param>
    /// <param name="typeFullName">类型全名(含命名空间,嵌套类型用+连接,如 Namespace.OuterClass+InnerClass)</param>
    /// <returns>类型(失败返回 null)</returns>
    public static Type LoadTypeFromAssembly(string assemblyPath, string typeFullName)
    {
        try
        {
            Assembly assembly = Assembly.LoadFrom(assemblyPath);
            return assembly.GetType(typeFullName);
        }
        catch
        {
            return null;
        }
    }
    #endregion
}

3.测试

using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

namespace ReflectionTest
{
    public class ReflectionTest:MonoBehaviour
    {
        #region 常量相关
        public class Config
        {
            public const string AppName = "MyApp";
            public const string Version = "1.0.0";
            public static readonly string Author = "Admin";//排除(readonly 非 const)
            public const int MaxCount = 100;//排除(非 string 类型)
        }
        #endregion

        #region 嵌套类相关
        public class OuterClass
        {
            public class PublicNested { }//公共嵌套类
            private class PrivateNested { }//私有嵌套类

            public class NestedA
            {
                public static string FieldA = "A";
                public static int NumA = 10;
            }
            public class NestedB
            {
                public static string FieldB = "B";
            }
        }
        #endregion

        #region 属性与字段相关
        public class User
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public static string AppName { get; } = "Test";
            private string password;
            private string nationality = "China";
        }
        #endregion

        #region 方法相关
        public class MyClass
        {
            public int Add(int a, int b) => a + b;
            public static int Multiply(int a, int b) => a * b;
            private string Combine(string a, string b) => $"{a}-{b}";
        }
        #endregion

        #region 实例创建相关
        public class Student
        {
            public Student() { }
            public Student(string name, int age)
            {
                Name = name;
                Age = age;
            }
            public string Name { get; set; }
            public int Age { get; }
        }
        #endregion

        #region 特性相关
        [AttributeUsage(AttributeTargets.Class)]
        public class DescriptionAttribute : Attribute
        {
            public string Text { get; }
            public DescriptionAttribute(string text) => Text = text;
        }
        [Description("用户信息类")]
        public class UserInfo { }

        public class Person
        {
            [Required]
            public string Name { get; set; }
        }
        public class RequiredAttribute : Attribute { }
        #endregion

        #region 程序集相关
        public interface IPlugin { void Run(); }
        public class PluginA : IPlugin { public void Run() { } }
        public abstract class AbstractPlugin : IPlugin { public abstract void Run(); }
        #endregion

        private void Start()
        {
            //常量相关
            var constStrings = ReflectionHelper.GetConstStringValues<Config>();
            var intConsts = ReflectionHelper.GetConstValues<Config, int>();

            //嵌套类相关
            var publicNesteds = ReflectionHelper.GetNestedClasses<OuterClass>(BindingFlags.Public);
            var allNesteds = ReflectionHelper.GetNestedClasses<OuterClass>(BindingFlags.Public | BindingFlags.NonPublic);
            var nestedFields = ReflectionHelper.GetNestedClassFields<OuterClass>();

            //属性与字段相关
            var props = ReflectionHelper.GetPublicProperties<User>();
            var user = new User { Name = "Zhang san", Age = 30 };
            var propValues = ReflectionHelper.GetPublicPropertyValues(user);
            user = new User { Name = "Li si" };
            bool success = ReflectionHelper.SetPublicPropertyValue(user, "Age", 25);
            var privateFields = ReflectionHelper.GetPrivateFields<User>();
            var fieldValue = ReflectionHelper.GetPrivateFieldValue(user, "nationality");

            //方法相关
            var obj = new MyClass();
            var result = ReflectionHelper.InvokePublicMethod(obj, "Add", 2, 3);
            var product = ReflectionHelper.InvokePublicStaticMethod<MyClass>("Multiply", 4, 5);
            var combined = ReflectionHelper.InvokePrivateMethod(obj, "Combine", "Hello", "World");

            //实例创建相关
            var studentA = ReflectionHelper.CreateInstance(typeof(Student)) as Student;
            var studentB = ReflectionHelper.CreateInstance(typeof(Student), "Wang wu", 28) as Student;
            var list = ReflectionHelper.CreateGenericInstance(typeof(List<>), typeof(string)) as List<string>;
            list.Add("Test");

            //特性相关
            var attr = ReflectionHelper.GetTypeAttribute<DescriptionAttribute, UserInfo>();
            var person = new Person();
            //获取到 Name 属性上的 RequiredAttribute 实例
            var requiredAttr = ReflectionHelper.GetPropertyAttribute<RequiredAttribute>(person, "Name");

            //程序集相关
            Assembly assembly = Assembly.GetExecutingAssembly();//当前程序集
            var plugins = ReflectionHelper.GetInterfaceImplementations<IPlugin>(assembly);
            //假设外部程序集 "Plugins.dll" 中有类 "MyPlugin"(命名空间:PluginNamespace)
            //Type pluginType = ReflectionHelper.LoadTypeFromAssembly(@"C:\Path\Plugins.dll", "PluginNamespace.MyPlugin");
        }
    }
}

4.总结

      ReflectionHelper反射助手类简化了C#反射操作,封装了七大核心能力:提取常量、处理嵌套类、操作属性与字段、调用方法、创建实例、解析特性、处理程序集,能高效实现运行时动态获取类型信息、操作成员及创建实例,适用于插件系统、依赖注入等动态场景

      好了,本次的分享到这里就结束啦,希望对你有所帮助~

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值