using System;
using global::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()
{
var t = Object.GetType();
switch (MemberType)
{
case ObjectValueType.Field:
{
var f = t.GetField(MemberName, MemberFlags);
object temp = null;
if (f is object)
{
temp = f.GetValue(Object);
f.SetValue(Object, ValueToPatch);
ValueToPatch = temp;
}
break;
}
case ObjectValueType.Property:
{
var p = t.GetProperty(MemberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
object temp = null;
if (p is object)
{
temp = p.GetValue(Object);
p.SetValue(Object, ValueToPatch);
ValueToPatch = temp;
}
break;
}
default:
{
throw new Exception("ValueType is invalid!");
break;
}
}
}
}
}