CodeGo.net>我如何调用一个方法与一个out参数?

我想要公开WebClient.DownloadDataInternal方法,如下所示:

[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有一个out参数,我不知道如何调用它。救命!

ldp615 asked 2020-08-02T08:30:36Z
2个解决方案
113 votes

您可以通过反射调用带有out参数的方法,就像其他任何方法一样。 区别在于返回的值将被复制回参数数组,因此您可以从调用函数访问它。

object[] args = new object[] { address, request };
_DownloadDataInternal.Invoke(this, args);
request = (WebRequest)args[1];
JaredPar answered 2020-08-02T08:31:08Z
18 votes
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);
    }
}
dtb answered 2020-08-02T08:30:48Z
translate from https://stackoverflow.com:/questions/2438065/how-can-i-invoke-a-method-with-an-out-parameter