Created
April 22, 2012 14:22
-
-
Save garyjohnson/2464327 to your computer and use it in GitHub Desktop.
WinRT Reflection Extension Methods
This file contains 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.Reflection; | |
namespace SharpSerializer | |
{ | |
public static class ExtensionMethods | |
{ | |
public static PropertyInfo GetProperty(this Type type, String propertyName) | |
{ | |
return type.GetTypeInfo().GetDeclaredProperty(propertyName); | |
} | |
public static MethodInfo GetMethod(this Type type, String methodName) | |
{ | |
return type.GetTypeInfo().GetDeclaredMethod(methodName); | |
} | |
public static bool IsSubclassOf(this Type type, Type parentType) | |
{ | |
return type.GetTypeInfo().IsSubclassOf(parentType); | |
} | |
public static bool IsAssignableFrom(this Type type, Type parentType) | |
{ | |
return type.GetTypeInfo().IsAssignableFrom(parentType.GetTypeInfo()); | |
} | |
public static bool IsEnum(this Type type) | |
{ | |
return type.GetTypeInfo().IsEnum; | |
} | |
public static bool IsPrimitive(this Type type) | |
{ | |
return type.GetTypeInfo().IsPrimitive; | |
} | |
public static Type GetBaseType(this Type type) | |
{ | |
return type.GetTypeInfo().BaseType; | |
} | |
public static bool IsGenericType(this Type type) | |
{ | |
return type.GetTypeInfo().IsGenericType; | |
} | |
public static Type[] GetGenericArguments(this Type type) | |
{ | |
return type.GetTypeInfo().GenericTypeArguments; | |
} | |
public static object GetPropertyValue(this Object instance, string propertyValue) | |
{ | |
return instance.GetType().GetTypeInfo().GetDeclaredProperty(propertyValue).GetValue(instance); | |
} | |
public static TypeInfo GetTypeInfo(this Type type) | |
{ | |
IReflectableType reflectableType = (IReflectableType)type; | |
return reflectableType.GetTypeInfo(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was getting some null reference exceptions on the GetDeclaredProperty call, so I refactored it and the exceptions stopped, just in case i added a try catch :)
Hope it helps, i'm new on this github thing so I won't contribute oficially yet, lol
public static object GetPropertyValue(this Object instance, string propertyValue)
{
try
{
PropertyInfo pi = instance.GetType().GetTypeInfo().GetDeclaredProperty(propertyValue);
return pi != null ? pi.GetValue(instance) : null;
}
catch
{
return null;
}
}