运行时动态转换对象的类型
有时候我们需要在动态运行的时候,转换一个对象的类型,这里提供一段小代码来完成这个工作:
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);}}}
参考:http://social.msdn.microsoft.com/forums/en-US/csharplanguage/thread/fe14d396-bc35-4f98-851d-ce3c8663cd79
TAG: