forked from GrahamKracker/OmegaCrosspathing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExtensions.cs
More file actions
42 lines (39 loc) · 1.52 KB
/
Extensions.cs
File metadata and controls
42 lines (39 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Reflection;
public static class ReflectionHelper
{
private static PropertyInfo GetPropertyInfo(Type type, string propertyName)
{
PropertyInfo propInfo = null;
do
{
propInfo = type.GetProperty(propertyName,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
type = type.BaseType;
}
while (propInfo == null && type != null);
return propInfo;
}
public static object GetPropertyValue(this object obj, string propertyName)
{
if (obj == null)
throw new ArgumentNullException("obj");
Type objType = obj.GetType();
PropertyInfo propInfo = GetPropertyInfo(objType, propertyName);
if (propInfo == null)
throw new ArgumentOutOfRangeException("propertyName",
string.Format("Couldn't find property {0} in type {1}", propertyName, objType.FullName));
return propInfo.GetValue(obj, null);
}
public static void SetPropertyValue(this object obj, string propertyName, object val)
{
if (obj == null)
throw new ArgumentNullException("obj");
Type objType = obj.GetType();
PropertyInfo propInfo = GetPropertyInfo(objType, propertyName);
if (propInfo == null)
throw new ArgumentOutOfRangeException("propertyName",
string.Format("Couldn't find property {0} in type {1}", propertyName, objType.FullName));
propInfo.SetValue(obj, val, null);
}
}