using System.Reflection;
namespace Pilz.Collections.SimpleHistory;
public class ObjectState : ObjectBase
{
///
/// The Object including the members to patch.
///
///
public object? Object { get; set; } = null;
///
/// The name of the Member to patch.
///
///
public string MemberName { get; set; } = "";
///
/// The Value that should be patched.
///
///
public object? ValueToPatch { get; set; } = null;
///
/// The member types to include at searching for the member.
///
///
public ObjectValueType MemberType { get; set; } = ObjectValueType.Field;
///
/// The Binding Flags that are used at searching for the member.
///
///
public BindingFlags MemberFlags { get; set; } = BindingFlags.Default;
///
/// Creates a new Instance of ObjectState from input.
///
/// The Object including the members to patch.
/// The name of the Member to patch.
/// The member types to include at searching for the member.
/// The Binding Flags that are used at searching for the member.
public ObjectState(object obj, string valname, object valToPatch, ObjectValueType valtype)
{
Object = obj;
MemberName = valname;
ValueToPatch = valToPatch;
MemberType = valtype;
}
///
/// Creates a new Instance of ObjectState.
///
public ObjectState()
{
}
internal void Patch()
{
if (Object is null)
return;
var t = Object.GetType();
switch (MemberType)
{
case ObjectValueType.Field:
if (t.GetField(MemberName, MemberFlags) is FieldInfo f)
{
var temp = f.GetValue(Object);
f.SetValue(Object, ValueToPatch);
ValueToPatch = temp;
}
break;
case ObjectValueType.Property:
if (t.GetProperty(MemberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static) is PropertyInfo p)
{
var temp = p.GetValue(Object);
p.SetValue(Object, ValueToPatch);
ValueToPatch = temp;
}
break;
default:
throw new Exception("ValueType is invalid!");
}
}
}