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

49 lines
1.6 KiB
C#

using System.Reflection;
using static System.Reflection.BindingFlags;
namespace InnovEnergy.Lib.Utils.Reflection;
public class Field : DataMember
{
private readonly Object? _Instance;
private readonly FieldInfo _FieldInfo;
public override String Name => _FieldInfo.Name;
public override Type Type => _FieldInfo.FieldType;
public override Boolean IsPublic => _FieldInfo.IsPublic;
public override Boolean IsPrivate => _FieldInfo.IsPrivate;
public override Boolean IsStatic => _FieldInfo.IsStatic;
public override Boolean IsWriteable => true;
public override Boolean IsReadable => true;
public override IEnumerable<Attribute> Attributes => _FieldInfo
.GetCustomAttributes(inherit: false)
.OfType<Attribute>();
internal Field(Object? instance, FieldInfo fieldInfo)
{
_Instance = instance;
_FieldInfo = fieldInfo;
}
public override Object? Get() => _FieldInfo.GetValue(_Instance) ;
public override void Set(Object value) => _FieldInfo.SetValue(_Instance, value);
}
public static class Fields
{
public static IEnumerable<Field> GetFields<T>(this T instance) where T : notnull
{
return instance
.GetType()
.GetFields(Instance | Static | Public | NonPublic)
.Select(fi => new Field(fi.IsStatic ? null : instance, fi));
}
public static IEnumerable<Field> OfInstance<T>(T instance) where T : notnull
{
return instance.GetFields();
}
}