-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReflectionHelper.cs
107 lines (96 loc) · 3.82 KB
/
ReflectionHelper.cs
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace DapperExtensions
{
public static class ReflectionHelper
{
private static List<Type> _simpleTypes = new List<Type>
{
typeof(byte),
typeof(sbyte),
typeof(short),
typeof(ushort),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(float),
typeof(double),
typeof(decimal),
typeof(bool),
typeof(string),
typeof(char),
typeof(Guid),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(byte[])
};
public static MemberInfo GetProperty(LambdaExpression lambda)
{
Expression expr = lambda;
for (; ; )
{
switch (expr.NodeType)
{
case ExpressionType.Lambda:
expr = ((LambdaExpression)expr).Body;
break;
case ExpressionType.Convert:
expr = ((UnaryExpression)expr).Operand;
break;
case ExpressionType.MemberAccess:
MemberExpression memberExpression = (MemberExpression)expr;
MemberInfo mi = memberExpression.Member;
return mi;
default:
return null;
}
}
}
public static IDictionary<string, object> GetObjectValues(object obj)
{
IDictionary<string, object> result = new Dictionary<string, object>();
if (obj == null)
{
return result;
}
foreach (var propertyInfo in obj.GetType().GetProperties())
{
string name = propertyInfo.Name;
object value = propertyInfo.GetValue(obj, null);
result[name] = value;
}
return result;
}
public static string AppendStrings(this IEnumerable<string> list, string seperator = ", ")
{
return list.Aggregate(
new StringBuilder(),
(sb, s) => (sb.Length == 0 ? sb : sb.Append(seperator)).Append(s),
sb => sb.ToString());
}
public static bool IsSimpleType(Type type)
{
Type actualType = type;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
actualType = type.GetGenericArguments()[0];
}
return _simpleTypes.Contains(actualType);
}
public static string GetParameterName(this IDictionary<string, object> parameters, string parameterName, char parameterPrefix)
{
return string.Format("{0}{1}_{2}", parameterPrefix, parameterName, parameters.Count);
}
public static string SetParameterName(this IDictionary<string, object> parameters, string parameterName, object value, char parameterPrefix)
{
string name = parameters.GetParameterName(parameterName, parameterPrefix);
parameters.Add(name, value);
return name;
}
}
}