using System.Reflection; using static System.Reflection.BindingFlags; namespace InnovEnergy.Lib.Utils.Reflection { public class Property : DataMember { private readonly Object? _Instance; private readonly PropertyInfo _PropertyInfo; internal Property(Object? instance, PropertyInfo propertyInfo) { _Instance = instance; _PropertyInfo = propertyInfo; } public override Boolean IsWriteable => _PropertyInfo.CanWrite; public override Boolean IsReadable => _PropertyInfo.CanRead; public override String Name => _PropertyInfo.Name; public override Type Type => _PropertyInfo.PropertyType; public override Boolean IsPublic => _PropertyInfo.IsPublic(); public override Boolean IsPrivate => _PropertyInfo.IsPrivate(); public override Boolean IsStatic => _PropertyInfo.IsStatic(); public override IEnumerable Attributes => GetAttributes(); public override Object? Get() => _PropertyInfo.GetValue(_Instance); public override void Set(Object value) => _PropertyInfo.SetValue(_Instance, value); public IEnumerable GetAttributes () where T : Attribute => _PropertyInfo .GetCustomAttributes(inherit: false) .OfType(); public Boolean HasAttribute () where T : Attribute => GetAttributes().Any(); } public static class Properties { public static IEnumerable GetProperties(this T instance) where T : notnull { return instance .GetType() .GetProperties(Instance | Static | Public | NonPublic) .Where(p => p.GetIndexParameters().Length == 0) // no indexers please .Select(pi => new Property(pi.IsStatic() ? null : instance, pi)); } public static IEnumerable OfInstance(T instance) where T : notnull { return instance.GetProperties(); } } internal static class PropertyInfoExtensions { public static Boolean IsStatic(this PropertyInfo i) { var getter = i.GetMethod; var setter = i.SetMethod; return (getter is not null && getter.IsStatic) || (setter is not null && setter.IsStatic); } public static Boolean IsPublic(this PropertyInfo i) { var getter = i.GetMethod; var setter = i.SetMethod; return (getter is not null && getter.IsPublic) || (setter is not null && setter.IsPublic); } public static Boolean IsPrivate(this PropertyInfo i) { var getter = i.GetMethod; var setter = i.SetMethod; return (getter is not null && getter.IsPrivate) || (setter is not null && setter.IsPrivate); } } }