Last active
February 3, 2017 14:57
-
-
Save morbidcamel101/61bf132d594eb8fe66b9e5a46e857bba to your computer and use it in GitHub Desktop.
Common reflection extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Reflection; | |
| using System.Web; | |
| namespace GCFinder.Models | |
| { | |
| public static class ReflectionUtil | |
| { | |
| public static T GetAttribute<T>(this MemberInfo memberInfo) where T : Attribute | |
| { | |
| return memberInfo.GetCustomAttributes(typeof(T), true).FirstOrDefault() as T; | |
| } | |
| public static T GetAttribute<T>(this ParameterInfo memberInfo) where T : Attribute | |
| { | |
| return memberInfo.GetCustomAttributes(typeof(T), true).FirstOrDefault() as T; | |
| } | |
| public static TypeCode ToTypeCode(this System.Type type) | |
| { | |
| switch (type.FullName) | |
| { | |
| case "System.Boolean": | |
| return TypeCode.Boolean; | |
| case "System.Int16": | |
| return TypeCode.Int16; | |
| case "System.Int32": | |
| return TypeCode.Int32; | |
| case "System.Int64": | |
| return TypeCode.Int64; | |
| case "System.DateTime": | |
| return TypeCode.DateTime; | |
| case "System.String": | |
| return TypeCode.String; | |
| case "System.Single": | |
| return TypeCode.Single; | |
| case "System.Double": | |
| return TypeCode.Double; | |
| case "System.Decimal": | |
| return TypeCode.Decimal; | |
| case "System.TimeSpan": | |
| return TypeCode.DateTime; | |
| default: | |
| return TypeCode.Object; | |
| } | |
| } | |
| public static bool ImplementsGenericInterface(this Type type, Type interfaceType) | |
| { | |
| if (interfaceType.GetGenericTypeDefinition() == interfaceType) | |
| return type.GetTypeInfo().ImplementedInterfaces.Any(x => x.GenericTypeArguments.Length > 0 | |
| && x.GetGenericTypeDefinition() == interfaceType); | |
| else | |
| return type.GetTypeInfo().ImplementedInterfaces.Any(x => x.GenericTypeArguments.Length > 0 | |
| && x == interfaceType); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment