登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

秒大刀 博客

好好学习 天天向上

 
 
 

日志

 
 
 
 

C#的几个实用动态方法  

2009-03-21 14:16:34|  分类: C# |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

    关于C#的运行时动态操作以前写过两篇《C# 运行时动态对象创建》、《C#动态方法调用》,本篇将再介绍几个实用函数,以方便使用。

 public static class RuntimeHelper
 {
  public static object InvokeMember(string methodName, object target, params object[] args)
  {
   return target.GetType().InvokeMember(methodName,
    System.Reflection.BindingFlags.InvokeMethod,
    null, target, args);
  }
  public static object InvokeStaticMember(string methodName, Type targetType, params object[] args)
  {
   return targetType.InvokeMember(methodName,
    System.Reflection.BindingFlags.Public
    | System.Reflection.BindingFlags.InvokeMethod
    | System.Reflection.BindingFlags.Static,
    null, null, args);
  }
  public static object InvokeGetProperty(string methodName, object target, params object[] args)
  {
   return target.GetType().InvokeMember(methodName,
    System.Reflection.BindingFlags.GetProperty,
    null, target, args);
  }
  public static object InvokeStaticGetProperty(string methodName, Type targetType, params object[] args)
  {
   return targetType.InvokeMember(methodName,
    System.Reflection.BindingFlags.GetProperty
    | System.Reflection.BindingFlags.Static,
    null, null, args);
  }
  public static T Parse<T>(string str)
  {
   return (T)InvokeStaticMember("Parse", typeof(T), str);
  }
  public static T Parse<T>(string str, T defaultValue)
  {
   T result; TryParse<T>(str, out result, defaultValue); return result;
  }
  public static bool TryParse<T>(string str, out T result, T defaultValue)
  {
   object[] args = new object[] { str, null };
   if ((bool)typeof(T).InvokeMember("TryParse",
    System.Reflection.BindingFlags.Public
    | System.Reflection.BindingFlags.InvokeMethod
    | System.Reflection.BindingFlags.Static,
    null, null, args))
   {
    result = (T)args[1]; return true;
   }
   else
   {
    result = defaultValue; return false;
   }
  }
 }


2011-6-14

Using C# dynamic to call static members

  评论这张
 
阅读(1425)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018