root / trunk / hammock / src / net35 / Hammock / Extensions / ObjectExtensions.cs @ 0eea575a
History | View | Annotate | Download (2.3 kB)
1 |
using System; |
---|---|
2 |
|
3 |
#if NETCF |
4 |
using System.Linq; |
5 |
#endif |
6 |
|
7 |
namespace Hammock.Extensions |
8 |
{ |
9 |
internal static class ObjectExtensions |
10 |
{ |
11 |
public static bool Implements(this object instance, Type interfaceType) |
12 |
{ |
13 |
return interfaceType.IsGenericTypeDefinition |
14 |
? instance.ImplementsGeneric(interfaceType) |
15 |
: interfaceType.IsAssignableFrom(instance.GetType()); |
16 |
} |
17 |
|
18 |
private static bool ImplementsGeneric(this Type type, Type targetType) |
19 |
{ |
20 |
var interfaceTypes = type.GetInterfaces(); |
21 |
foreach (var interfaceType in interfaceTypes) |
22 |
{ |
23 |
if (!interfaceType.IsGenericType) |
24 |
{ |
25 |
continue; |
26 |
} |
27 |
|
28 |
if (interfaceType.GetGenericTypeDefinition() == targetType) |
29 |
{ |
30 |
return true; |
31 |
} |
32 |
} |
33 |
|
34 |
var baseType = type.BaseType; |
35 |
if (baseType == null) |
36 |
{ |
37 |
return false; |
38 |
} |
39 |
|
40 |
return baseType.IsGenericType |
41 |
? baseType.GetGenericTypeDefinition() == targetType |
42 |
: baseType.ImplementsGeneric(targetType); |
43 |
} |
44 |
|
45 |
private static bool ImplementsGeneric(this object instance, Type targetType) |
46 |
{ |
47 |
return instance.GetType().ImplementsGeneric(targetType); |
48 |
} |
49 |
|
50 |
public static Type GetDeclaredTypeForGeneric(this object instance, Type interfaceType) |
51 |
{ |
52 |
return instance.GetType().GetDeclaredTypeForGeneric(interfaceType); |
53 |
} |
54 |
|
55 |
public static Type GetDeclaredTypeForGeneric(this Type baseType, Type interfaceType) |
56 |
{ |
57 |
var type = default(Type); |
58 |
|
59 |
if (baseType.ImplementsGeneric(interfaceType)) |
60 |
{ |
61 |
#if NETCF |
62 |
var generic = baseType.GetInterfaces() |
63 |
.Single(i => i.FullName.Equals(interfaceType.FullName)); |
64 |
#else |
65 |
var generic = baseType.GetInterface(interfaceType.FullName, true); |
66 |
#endif |
67 |
if (generic.IsGenericType) |
68 |
{ |
69 |
var args = generic.GetGenericArguments(); |
70 |
if (args.Length == 1) |
71 |
{ |
72 |
type = args[0]; |
73 |
} |
74 |
} |
75 |
} |
76 |
|
77 |
return type; |
78 |
} |
79 |
} |
80 |
} |