2010-09-20 84 views
0

我有一个从远程网站接收数据的WebClient实例。我引用的DownloadProgressChanged事件处理程序,我试图访问InnerBuffer,这是WebClient的DownloadBitsState嵌套类(设置为私有)的内部场。访问内部字段[WebClient]

我使用下面的代码就在DownloadProgressChanged事件处理程序:

WebClient c = (WebClient)sender; 
Type t = typeof(WebClient).GetNestedType("DownloadBitsState", BindingFlags.NonPublic); 

FieldInfo m = t.GetField("InnerBuffer",BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); 

Debug.WriteLine(m.GetValue(c).ToString()); 

我得到一个运行时错误:FieldAccessExceptionSystem.Net.WebClient+DownloadBitsState.InnerBuffer

有什么办法,我可以读取这个域或我根本无法读取内部字段的内容?

回答

0

您想要的字段可能是只写的。使用反射器查看源代码以查看发生了什么。如果它只写,那么你将需要访问私人领域。

另外:他传递参考使用m.GetValue(c)因为c是发件人的实例转换为Webclient。

BTW:确保WebClient不为空。

- 编辑:发布我的答案后,我意识到你试图访问未实例化的类型的属性。卫生署! Webclient是否有一个拥有DownloadBitsState实例的属性?请使用,进而拉动财产

- 编辑:看代码,在Web客户端实例化DownloadBitsState的唯一方法是private byte[] DownloadBits()

private byte[] DownloadBits(WebRequest request, Stream writeStream, CompletionDelegate completionDelegate, AsyncOperation asyncOp) 
{ 
    WebResponse response = null; 
    DownloadBitsState state = new DownloadBitsState(request, writeStream, completionDelegate, asyncOp, this.m_Progress, this); 
    if (state.Async) 
    { 
     request.BeginGetResponse(new AsyncCallback(WebClient.DownloadBitsResponseCallback), state); 
     return null; 
    } 
    response = this.m_WebResponse = this.GetWebResponse(request); 
    int bytesRetrieved = state.SetResponse(response); 
    while (!state.RetrieveBytes(ref bytesRetrieved)) 
    { 
    } 
    state.Close(); 
    return state.InnerBuffer; 
} 

所以,你真的不能做你想要的是什么你想要的方式。

+0

这已经在我的回答的评论中全部讨论过了。此外,它现在看来,这是Windows Phone 7. – leppie 2010-09-21 18:12:54

+0

Ieppie,其中一些是,但我已经给了他一个'不'的确切答案,他不能这样做,因为如何使用DownloadBitsState。 – 2010-09-21 18:53:57

1

该实例不正确。

FieldInfo需要DownloadBitsState实例时,您无法传递WebClient类型的实例。

+0

我很好奇 - 我将如何传递实际的WebClient实例,而不是t - 这只是一种没有实际数据的类型? – 2010-09-20 03:51:57

+0

即使我使用Debug.WriteLine(m.GetValue(c.GetType()。GetNestedType(“DownloadBitsState”,BindingFlags.NonPublic))。ToString()); - 它仍会抛出相同的异常。 – 2010-09-20 04:23:26

+0

@Dennis Delimarsky:那么现在它是一个'Type'实例。你想做什么? “WebClient”中没有看到“DownloadBitsState”的任何实例。 – leppie 2010-09-20 08:44:10