-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectionExtension.cs
More file actions
40 lines (33 loc) · 1023 Bytes
/
ReflectionExtension.cs
File metadata and controls
40 lines (33 loc) · 1023 Bytes
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
using System;
using System.Reflection;
namespace VoiceOnlineBot
{
public static class ReflectionExtension
{
public static Object GetPropValue(this object obj, string name)
{
foreach (String part in name.Split('.'))
{
if (obj == null) { return null; }
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
return obj;
}
public static T GetPropValue<T>(this object obj, string name)
{
Object retval = GetPropValue(obj, name);
if (retval == null) { return default(T); }
// throws InvalidCastException if types are incompatible
return (T)retval;
}
public static void SetValue(this object obj, string name, object value)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(name);
propertyInfo.SetValue(obj, Convert.ChangeType(value, propertyInfo.PropertyType), null);
// throws InvalidCastException if types are incompatible
}
}
}