using System.Reflection; namespace EC.Util.Common; public class ReflectUtil { private static readonly BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; public static bool ContainProperty(object instance, string propertyName) { if (instance == null || string.IsNullOrEmpty(propertyName)) return false; PropertyInfo? property = instance.GetType()?.GetProperty(propertyName, bindingAttr); return property != null; } public static T? GetProperty(object instance, string propertyName) { if (instance == null || string.IsNullOrEmpty(propertyName)) return default; PropertyInfo? property = instance.GetType()?.GetProperty(propertyName, bindingAttr); try { return (T?)property?.GetValue(instance, null); } catch (Exception) { return default; } } public static bool GetProperty(object instance, string propertyName, out T? val) { val = GetProperty(instance, propertyName); return val != null; } public static bool ContainField(object instance, string propertyName) { if (instance == null || string.IsNullOrEmpty(propertyName)) return false; FieldInfo? field = instance.GetType()?.GetField(propertyName, bindingAttr); return field != null; } public static T? GetField(object instance, string propertyName) { if (instance == null || string.IsNullOrEmpty(propertyName)) return default; FieldInfo? field = instance.GetType()?.GetField(propertyName, bindingAttr); try { return (T?)field?.GetValue(instance); } catch (Exception) { return default; } } public static bool GetField(object instance, string propertyName, out T? val) { val = GetField(instance, propertyName); return val != null; } public static void SetField(object instance, string propertyName, T? val) { if (instance == null || string.IsNullOrEmpty(propertyName)) return; FieldInfo? field = instance.GetType()?.GetField(propertyName, bindingAttr); try { field?.SetValue(instance, val); } catch (Exception) { } } public static MethodInfo? GetMethod(object instance, string name) { MethodInfo? method = instance.GetType().GetMethod(name); return method; } public static T? RunMethod(object instance, string name, object?[]? parameters) { try { MethodInfo? method = instance.GetType().GetMethod(name); return (T?)method?.Invoke(instance, parameters); } catch (Exception) { return default; } } }