using System.Reflection; using InnovEnergy.Lib.Utils; namespace InnovEnergy.App.Collector.Utils; public readonly struct Property { public Object Instance { get; } private PropertyInfo PropertyInfo { get; } public Property(Object instance, PropertyInfo propertyInfo) { Instance = instance ?? throw new ArgumentException("instance cannot be null", nameof(instance)); PropertyInfo = propertyInfo; } public Boolean IsWritable => PropertyInfo.CanWrite; public Boolean IsReadable => PropertyInfo.CanRead; public IEnumerable Attributes => GetAttributes(); public String Name => PropertyInfo.Name; public Type Type => PropertyInfo.PropertyType; public Object Get() => PropertyInfo.GetValue(Instance); public T Get() => (T) PropertyInfo.GetValue(Instance); public 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 PropertyExtensions { public static IEnumerable GetProperties(this Object instance) { return instance .GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public) .Unless(p => p.GetIndexParameters().Any()) // no indexers please .Select(pi => new Property(instance, pi)); } }