How can I invoke a method with an out parameter?

2019-01-13 12:44发布

I want expose WebClient.DownloadDataInternal method like below:

[ComVisible(true)]
public class MyWebClient : WebClient
{
    private MethodInfo _DownloadDataInternal;

    public MyWebClient()
    {
        _DownloadDataInternal = typeof(WebClient).GetMethod("DownloadDataInternal", BindingFlags.NonPublic | BindingFlags.Instance);
    }

    public byte[] DownloadDataInternal(Uri address, out WebRequest request)
    {
        _DownloadDataInternal.Invoke(this, new object[] { address, out request });
    }

}

WebClient.DownloadDataInternal has a out parameter, I don't know how to invoke it. Help!

2条回答
仙女界的扛把子
2楼-- · 2019-01-13 13:13

You invoke a method with an out parameter via reflection just like any other method. The difference is that the returned value will be copied back into the parameter array so you can access it from the calling function.

object[] args = new object[] { address, request };
_DownloadDataInternal.Invoke(this, args);
request = (WebRequest)args[1];
查看更多
闹够了就滚
3楼-- · 2019-01-13 13:23
public class MyWebClient : WebClient
{
    delegate byte[] DownloadDataInternal(Uri address, out WebRequest request);

    DownloadDataInternal downloadDataInternal;

    public MyWebClient()
    {
        downloadDataInternal = (DownloadDataInternal)Delegate.CreateDelegate(
            typeof(DownloadDataInternal),
            this,
            typeof(WebClient).GetMethod(
                "DownloadDataInternal",
                BindingFlags.NonPublic | BindingFlags.Instance));
    }

    public byte[] DownloadDataInternal(Uri address, out WebRequest request)
    {
        return downloadDataInternal(address, out request);
    }
}
查看更多
登录 后发表回答