zoukankan      html  css  js  c++  java
  • 如何通过反射调用带有ref或者out的参数的方法[迁移]

    原帖放在GCDN上,由于GCDN做了整合调整,现在关注产品交流等原因GCDN Blog关闭了,只好把一些有用点的搬过来了。

    2009年8月13日 12:29 by winking

    写这篇博客,原起今天CyljXu问我一个问题:如何通过反射调用带有ref或者out的参数的方法?想着可能其他人也会遇到这个问题,权且记录下来,以备后行者搜索到。

    这个在MSDN上有解释,参考 MethodBase.Invoke方法

    public Object Invoke(
    Object obj,
    Object[] parameters
    )

    参数

    obj 类型:System.Object

    对其调用方法或构造函数的对象。如果方法是静态的,则忽略此参数。如果构造函数是静态的,则此参数必须为 null 引用(在 Visual Basic 中为 Nothing 或定义该构造函数的类的实例。

    parameters 类型: System.Object[]

    调用的方法或构造函数的参数列表。这是一个对象数组,这些对象与要调用的方法或构造函数的参数具有相同的数量、顺序和类型。如果没有任何参数,则 parameters 应为 null 引用(在 Visual Basic 中为 Nothing

    如果此实例所表示的方法或构造函数采用 ref 参数(在 Visual Basic 中为 ByRef ),使用此函数调用该方法或构造函数时, 该参数不需要任何特殊属性 。如果数组中的对象未用值来显式初始化,则该对象将包含该对象类型的默认值。对于引用类型的元素,该值为 null 引用(在 Visual Basic 中为 Nothing 。对于值类型的元素,该值为 0、0.0 或 false ,具体取决于特定的元素类型。

    那么该如何调用并处理传值呢?请看如下示例:

    1 class Program
    2 {
    3 static void Main(string[] args)
    4 {
    5 string content = "main"; //#1 variable
    6   MethodInfo testMethod = typeof(Program).GetMethod("TestMethod",
    7 BindingFlags.Static | BindingFlags.NonPublic);
    8 if (testMethod != null)
    9 {
    10 // Following way can not take content back.
    11 // -------------------------------------
    12   testMethod.Invoke(null, new object[] { content /* #1 variable */ });
    13 Console.WriteLine(content); // #1 variable, Output is: main
    14 // -------------------------------------
    15  
    16
    17 object[] invokeArgs = new object[] { content /* #1 variable */ };
    18 testMethod.Invoke(null, invokeArgs);
    19 content = (string)invokeArgs[0]; // #2 variable, bypass from invoke, set to content.
    20   Console.WriteLine(content); // #2 variable, Output is: test
    21   }
    22 }
    23
    24 static void TestMethod(ref string arg)
    25 {
    26 arg = "test"; // #2 variable, wanna bypass to main process.
    27   }
    28 }

    To be the apostrophe which changed “Impossible” into “I’m possible”
    ----------------------------------------------------
    WinkingZhang's Blog (http://winkingzhang.cnblogs.com)
    GCDN(http://gcdn.grapecity.com/cs)
  • 相关阅读:
    51degress.mobi与wurfl项目的对比
    低版本的51degrees.mobi 1.2.0.5 用UserAgent获取手机硬件型号,并升级最新的WURFL硬件包
    RedGate系列工具,开发必备
    VS中代码显示虚竖线,代码格式标记 Indent Guides
    asp.net下CKFinder IE9以下浏览器中上传图片文件时提示“无效文件名或文件夹名称”的解决方法
    让MySoft.Data也能有Discuz!NT的数据库查询分析工具
    恶意访问网站的策略处理,IP访问限制
    【转载】Asp.Net 全生命周期
    如何在解决方案中新建子网站,Discuz项目子网站技术
    博客园电子期刊2009年8月刊发布啦
  • 原文地址:https://www.cnblogs.com/winkingzhang/p/1645065.html
Copyright © 2011-2022 走看看