Skip to content

Commit 14fa2d1

Browse files
authored
GetValue and SetValue extensions (#17)
1 parent 18d04e1 commit 14fa2d1

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

OWML.Events/TypeExtensions.cs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Reflection;
3+
using OWML.Common;
34

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

26+
public static T GetValue<T>(this object obj, string name)
27+
{
28+
var type = obj.GetType();
29+
var field = type.GetAnyField(name);
30+
if (field != null)
31+
{
32+
return (T)field.GetValue(obj);
33+
}
34+
var property = type.GetAnyProperty(name);
35+
if (property != null)
36+
{
37+
return (T)property.GetValue(obj, null);
38+
}
39+
ModBehaviour.ModHelper.Console.WriteLine($"Couldn't find field or property with name {name} on {type.Name}");
40+
return default;
41+
}
42+
43+
public static void SetValue(this object obj, string name, object value)
44+
{
45+
var type = obj.GetType();
46+
var field = type.GetAnyField(name);
47+
if (field != null)
48+
{
49+
field.SetValue(obj, value);
50+
return;
51+
}
52+
var property = type.GetAnyProperty(name);
53+
if (property != null)
54+
{
55+
property.SetValue(obj, value, null);
56+
return;
57+
}
58+
ModBehaviour.ModHelper.Console.WriteLine($"Couldn't find field or property with name {name} on {type.Name}");
59+
}
60+
2561
}
26-
}
62+
}

0 commit comments

Comments
 (0)