运行时动态转换对象的类型
有时候我们需要在动态运行的时候,转换一个对象的类型,这里提供一段小代码来完成这个工作:
public class DynamicCastType{static MethodInfo castMethod;
public static object Cast(object obj, Type targetType){if (castMethod == null){castMethod = typeof(DynamicCastType).GetMethod("CastIt", BindingFlags.NonPublic | BindingFlags.Static);}return castMethod.MakeGenericMethod(targetType).Invoke(null, new object[] { obj });}static T CastIt<T>(object obj){try
{return (T)obj;
}catch
{return default(T);}}}