Innovenergy_trunk/csharp/Lib/Utils/Reflection/Property.cs

87 lines
3.1 KiB
C#
Raw Normal View History

2023-04-05 15:43:27 +00:00
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<Attribute> Attributes => GetAttributes<Attribute>();
public override Object? Get() => _PropertyInfo.GetValue(_Instance);
public override 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 Properties
{
public static IEnumerable<Property> GetProperties<T>(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<Property> OfInstance<T>(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);
}
}
}