使用反射获取属性属性

时间:2010-10-06 14:48:47

标签: c# .net vb.net reflection

我试图通过执行以下操作来获取本地路径的值:

  Dim bar As WebProxy = WebProxy.GetDefaultProxy
  Dim scriptEngine = bar.GetType().GetProperty("ScriptEngine", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
  Dim acs As PropertyInfo = scriptEngine.PropertyType().GetProperty("AutomaticConfigurationScript", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
  Dim localPath As PropertyInfo = acs.PropertyType().GetProperty("LocalPath", Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance)
  Dim value As String = localPath.GetValue(acs, Nothing).ToString

我很确定这里的问题是我将PropertyInfo对象传递给localPath.GetValue,而不是实际的对象本身。唯一的问题是我无法施放

的结果
Dim acs As PropertyInfo = scriptEngine.PropertyType().GetProperty("AutomaticConfigurationScript", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)

进入System.Uri AutomaticConfigurationScript并传入,因此我收到错误“对象与目标类型不匹配”。

有什么想法吗?

P.S我意识到这不是一个c#问题,但不想限制我标记它的可能答案,因为它是一个.Net问题,如果我在C#中收到答案,我可以翻译。

1 个答案:

答案 0 :(得分:1)

您需要在每一步获取实际对象,并使用它来获取下一个属性:

Dim bar As WebProxy = WebProxy.GetDefaultProxy

Dim scriptEngineProperty = bar.GetType().GetProperty("ScriptEngine", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
Dim scriptEngineObject as Object = scriptEngineProperty.GetValue(bar, Nothing)

Dim acsProperty As PropertyInfo = scriptEngineObject.GetType().GetProperty("AutomaticConfigurationScript", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
Dim acsObject as Object = acsProperty.GetValue(scriptEngineObject, Nothing)

Dim localPathProperty As PropertyInfo = acsObject.GetType().GetProperty("LocalPath", Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance)
Dim value As String = localPath.GetValue(acsObject, Nothing).ToString