Skip to content

Commit

Permalink
GetValue and SetValue extensions (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
amazingalek authored Dec 21, 2019
1 parent 18d04e1 commit 14fa2d1
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion OWML.Events/TypeExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Reflection;
using OWML.Common;

namespace OWML.Events
{
Expand All @@ -22,5 +23,40 @@ public static FieldInfo GetAnyField(this Type type, string name)
return type.GetField(name, Flags);
}

public static T GetValue<T>(this object obj, string name)
{
var type = obj.GetType();
var field = type.GetAnyField(name);
if (field != null)
{
return (T)field.GetValue(obj);
}
var property = type.GetAnyProperty(name);
if (property != null)
{
return (T)property.GetValue(obj, null);
}
ModBehaviour.ModHelper.Console.WriteLine($"Couldn't find field or property with name {name} on {type.Name}");
return default;
}

public static void SetValue(this object obj, string name, object value)
{
var type = obj.GetType();
var field = type.GetAnyField(name);
if (field != null)
{
field.SetValue(obj, value);
return;
}
var property = type.GetAnyProperty(name);
if (property != null)
{
property.SetValue(obj, value, null);
return;
}
ModBehaviour.ModHelper.Console.WriteLine($"Couldn't find field or property with name {name} on {type.Name}");
}

}
}
}

0 comments on commit 14fa2d1

Please sign in to comment.