为什么我使用Type.GetField()离开返回null?

时间:2018-04-14 09:17:08

标签: c# reflection

我使用GetField()获取selenium的PID,但是当我尝试获取“ProcessId”时它会返回null,可以看到img,ProcessId字段是非空的。 这是我的代码:

public void tes(ChromeDriver driver) {
            var flag = System.Reflection.BindingFlags.NonPublic
                          | System.Reflection.BindingFlags.Instance;
            var executorField = typeof(OpenQA.Selenium.Remote.RemoteWebDriver)
                .GetField("executor",
                          System.Reflection.BindingFlags.NonPublic
                          | System.Reflection.BindingFlags.Instance);
            object executor = executorField.GetValue(driver);
            var Service = executor.GetType().GetField("service", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            object remoteServerPidField = Service.GetValue(executor);
            var pid = remoteServerPidField.GetType().GetField("ProcessId", BindingFlags.Instance | BindingFlags.Static);
        }

enter image description here

1 个答案:

答案 0 :(得分:2)

ProcessId不是字段,而是属性。您应该使用.GetProperty代替。

那就是说,该物业是公开的,你已经有了一个服务实例,所以我不确定你为什么需要这里的反思 -

var service = executor.GetType()
                .GetField("service", BindingFlags.NonPublic | BindingFlags.Instance)
                .GetValue(executor) as ... ; // whatever type the 'service' is

var pid = service?.ProcessId;