Reflection中對於out類型的擷取

來源:互聯網
上載者:User
先看這個代碼:using System;

namespace AppTest
{
    public class AppTest1 
    {
        public void SetValue(string value1, out string value2) 
        {
            value2 = "hello";
        }

        public void SetValue(string value1)
        {
            
        }
    }
}

我的目的,是通過反射,得到SetValue帶有兩個參數的這個MethodInfo。一般的,我們會調用包含GetMethod中第5個或者第6個重載的方法,即,包含ParameterModifier的那個方法。但是不知道為什麼,返回的MethodInfo總是null。後來google了一下GetMethod ParameterModifier,到.net247上找到了一個答案。代碼修改為這樣,可以了:            Assembly asm = Assembly.LoadFrom(@"D:\Programs\vs.net\SerialGen\Test\bin\Debug\test.dll");
            Type t = asm.GetType("AppTest.AppTest1");
            
            // 這段定義是下面第一個GetMethod使用的
            ParameterModifier[] pm = new ParameterModifier[2];
            pm[0] = new ParameterModifier(1);
            pm[0][0] = false;
            pm[1] = new ParameterModifier(1);
            pm[1][0] = true;

            // 這行,返回的mi是null
            MethodInfo mi  = t.GetMethod("SetValue",BindingFlags.DeclaredOnly,null,new Type[]{typeof(string),typeof(string)},pm);
            // 這行,返回的是正確的
            MethodInfo mi2 = t.GetMethod("SetValue",new Type[]{typeof(string),Type.GetType("System.String&")});

第二個GetMethod中的TypeList,直接寫成了System.String&就可以了。
第一種方式,為什麼不可以?對於上面的pm的賦值,也這樣寫過:            ParameterModifier[] pm = new ParameterModifier[1];
            pm[0] = new ParameterModifier(2);
            pm[0][0] = false;
            pm[0][1] = true;

不過,也不正確。,不知道,這玩藝到底怎麼用啊?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.