如何获取某些元数据的私有字段的值?

发布于 2025-01-12 16:30:24 字数 248 浏览 3 评论 0原文

我正在使用名为 DevExpress.Xpo 的 NuGet 包,其 DataStorePool 类有一个名为 connections 的私有 int。我需要以某种方式在另一个类中使用它的值,但 DataStorePool 类被锁定为“元数据”,因此我无法将 int 设置为 public 也无法创建方法返回它。我该如何获取 int 的值?

I'm using a NuGet Package called DevExpress.Xpo and its DataStorePool class has a private int called connections. I need to somehow use its value in another class, but the DataStorePool class is locked as "metadata", so I can't set the int to public nor create a method that returns it. What can I do to obtain the value of the int?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦言归人 2025-01-19 16:30:25

您可以创建一个扩展方法来执行此操作。
它可以看起来像这样:

Foo foo = new Foo();
string c = foo.GetFieldValue<string>("_bar");

以及创建它的方式:

public static class ReflectionExtensions {
    public static T GetFieldValue<T>(this object obj, string name) {
        // Set the flags so that private and public fields from instances will be found
        var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        var field = obj.GetType().GetField(name, bindingFlags);
        return (T)field?.GetValue(obj);
    }
}

或者

您可以使用 BindingFlags.NonPublic 和 BindingFlags.Instance 标志

FieldInfo[] fields = myType.GetFields(
                         BindingFlags.NonPublic | 
                         BindingFlags.Instance);

您可以在此处阅读如何使用反射获取它

You could create an extension method to do it.
It can look like that:

Foo foo = new Foo();
string c = foo.GetFieldValue<string>("_bar");

And the way to create it:

public static class ReflectionExtensions {
    public static T GetFieldValue<T>(this object obj, string name) {
        // Set the flags so that private and public fields from instances will be found
        var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        var field = obj.GetType().GetField(name, bindingFlags);
        return (T)field?.GetValue(obj);
    }
}

OR

You can use BindingFlags.NonPublic and BindingFlags.Instance flags

FieldInfo[] fields = myType.GetFields(
                         BindingFlags.NonPublic | 
                         BindingFlags.Instance);

OR

You could read how to get it with using reflection here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文