This repository was archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathReflectionExtensions.cs
More file actions
73 lines (61 loc) · 2.72 KB
/
Copy pathReflectionExtensions.cs
File metadata and controls
73 lines (61 loc) · 2.72 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace GitHub.Extensions
{
public static class ReflectionExtensions
{
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
Guard.ArgumentNotNull(assembly, nameof(assembly));
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}
public static bool HasInterface(this Type type, Type targetInterface)
{
Guard.ArgumentNotNull(type, nameof(type));
Guard.ArgumentNotNull(targetInterface, nameof(targetInterface));
if (targetInterface.IsAssignableFrom(type))
return true;
return type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == targetInterface);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
public static string GetCustomAttributeValue<T>(this Assembly assembly, string propertyName) where T : Attribute
{
Guard.ArgumentNotNull(assembly, nameof(assembly));
Guard.ArgumentNotEmptyString(propertyName, nameof(propertyName));
if (assembly == null || string.IsNullOrEmpty(propertyName)) return string.Empty;
object[] attributes = assembly.GetCustomAttributes(typeof(T), false);
if (attributes.Length == 0) return string.Empty;
var attribute = attributes[0] as T;
if (attribute == null) return string.Empty;
var propertyInfo = attribute.GetType().GetProperty(propertyName);
if (propertyInfo == null) return string.Empty;
var value = propertyInfo.GetValue(attribute, null);
return value.ToString();
}
public static T CreateUninitialized<T>()
{
// WARNING: THIS METHOD IS PURE EVIL!
// Only use this in cases where T is sealed and has an internal ctor and
// you're SURE the API you're passing it into won't do anything interesting with it.
// Even then, consider refactoring.
return (T)FormatterServices.GetUninitializedObject(typeof(T));
}
public static void Invoke(object obj, string methodName, params object[] parameters)
{
var method = obj.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
method.Invoke(obj, parameters);
}
}
}