有时候我们需要在动态运行的时候,转换一个对象的类型,这里提供一段小代码来完成这个工作:

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

相关文章:

  • 2021-07-21
  • 2022-12-23
  • 2022-12-23
  • 2021-10-05
  • 2022-03-01
  • 2022-02-05
猜你喜欢
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-24
  • 2022-01-10
相关资源
相似解决方案