Repository navigation
Expand file tree
/
Copy pathmethodof.cs
More file actions
110 lines (93 loc) · 2.63 KB
/
Copy pathmethodof.cs
File metadata and controls
110 lines (93 loc) · 2.63 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
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
108
109
110
/* Date: 6.9.2014, TDelegateime: 12:17 */
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace IllidanS4.SharpUtils.Reflection
{
public struct methodof<TDelegate> : IEquatable<methodof<TDelegate>>, IEquatable<MethodInfo> where TDelegate : class
{
public MethodBase Value{
get; private set;
}
static methodof()
{
Type t = typeof(TDelegate);
if(!typeof(Delegate).IsAssignableFrom(t))
{
throw new TypeLoadException("Generic argument must be a delegate type.");
}
}
public methodof(TDelegate method) : this()
{
Value = ((Delegate)(object)method).Method;
}
public methodof(Expression<TDelegate> expr) : this()
{
NewExpression ctor = expr.Body as NewExpression;
if(ctor != null)
{
Value = ctor.Constructor;
}else{
MethodCallExpression call = expr.Body as MethodCallExpression;
if(call == null) throw new ArgumentException("Expression must be MethodCallExpression or NewExpression.", "expr");
Value = call.Method;
}
}
public static implicit operator MethodInfo(methodof<TDelegate> m)
{
return m.Value as MethodInfo;
}
public static implicit operator ConstructorInfo(methodof<TDelegate> m)
{
return m.Value as ConstructorInfo;
}
public static implicit operator MethodBase(methodof<TDelegate> m)
{
return m.Value;
}
public static implicit operator TDelegate(methodof<TDelegate> m)
{
MethodInfo mi = m.Value as MethodInfo;
if(mi != null)
{
return (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), mi);
}else{
return null;
}
}
/*public static implicit operator methodof<TDelegate>(TDelegate m)
{
return new methodof<TDelegate>(m);
}*/
public static implicit operator methodof<TDelegate>(Expression<TDelegate> expr)
{
return new methodof<TDelegate>(expr);
}
#region Equals and GetHashCode implementation
public override bool Equals(object obj)
{
return ((obj is methodof<TDelegate>) && Equals((methodof<TDelegate>)obj)) || ((obj is TDelegate) && Equals((TDelegate)obj)) || ((obj is MethodInfo) && Equals((MethodInfo)obj));
}
public bool Equals(methodof<TDelegate> other)
{
return Object.Equals(this.Value, other.Value);
}
public bool Equals(MethodInfo other)
{
return Object.Equals((MethodInfo)this, other);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public static bool operator ==(methodof<TDelegate> lhs, methodof<TDelegate> rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(methodof<TDelegate> lhs, methodof<TDelegate> rhs)
{
return !(lhs == rhs);
}
#endregion
}
}