70 private static bool CanCast<T>(
this Type baseType,
string castMethodName)
72 Type targetType = typeof(T);
74 return baseType.GetMethods(BindingFlags.Public | BindingFlags.Static)
75 .Where(mi => mi.Name == castMethodName && mi.ReturnType == targetType)
78 ParameterInfo pi = mi.GetParameters()
81 return pi !=
null && pi.ParameterType == baseType;
96 private static T
Cast<T>(
this object obj,
string castMethodName)
98 Type objType = obj.GetType();
100 MethodInfo conversionMethod = objType.GetMethods(BindingFlags.Public | BindingFlags.Static)
101 .Where(mi => mi.Name == castMethodName && mi.ReturnType == typeof(T))
102 .SingleOrDefault(mi =>
104 ParameterInfo pi = mi.GetParameters()
107 return pi !=
null && pi.ParameterType == objType;
111 if (conversionMethod !=
null)
113 return (T)conversionMethod.Invoke(
null,
118 throw new InvalidCastException($
"No method to cast {objType.FullName} to {typeof(T).FullName}");