49 lines
1.5 KiB
C#
49 lines
1.5 KiB
C#
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<Attribute> Attributes => GetAttributes<Attribute>();
|
|
|
|
public String Name => PropertyInfo.Name;
|
|
public Type Type => PropertyInfo.PropertyType;
|
|
|
|
public Object Get() => PropertyInfo.GetValue(Instance);
|
|
|
|
public T Get<T>() => (T) PropertyInfo.GetValue(Instance);
|
|
|
|
public void Set(Object value) => PropertyInfo.SetValue(Instance, value);
|
|
|
|
public IEnumerable<T> GetAttributes<T> () where T : Attribute => PropertyInfo
|
|
.GetCustomAttributes(inherit: false)
|
|
.OfType<T>();
|
|
|
|
public Boolean HasAttribute<T> () where T : Attribute => GetAttributes<T>().Any();
|
|
|
|
}
|
|
|
|
public static class PropertyExtensions
|
|
{
|
|
public static IEnumerable<Property> 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));
|
|
}
|
|
} |