如何使用反射获取私有字段的值? [英] How to get the value of private field using reflection?

查看:38
本文介绍了如何使用反射获取私有字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,需要访问类的私有字段.例如:

I ran into a problem that I need to access to private field of a class. For example:

class MyClass 
{
    private string someString;

    public MyClass( string someStringValue )
    {
        someString = someStringValue;
    }
}

如何在 MyClass 之外获取 someString 的值?

How can I get the value of someString outside MyClass ?

抱歉,我不能在这里使用属性,因为实际的生产代码是受保护的.我是一名 QA/Dev,我需要一种方法来将这些私有化以编写用户验收测试.所以我不能更改生产代码.你能帮忙吗?

Sorry, I cannot use property here since the the actual production code is protected. I'm a QA/Dev, I need a way to get those private for writing User Acceptance Test. So I cannot change production code. Can you help?

推荐答案

正如其他人所说,由于该字段是私有的,您不应该尝试使用普通代码来获取它.唯一可以接受的情况是在单元测试期间,即便如此,您也需要一个很好的理由来这样做(例如将私有变量设置为 null,以便异常块中的代码将被命中并可以进行测试).

As others have said, since the field is private you should not be trying to get it with normal code. The only time this is acceptable is during unit testing, and even then you need a good reason to do it (such as setting a private variable to null so that code in an exception block will be hit and can be tested).

您可以使用类似下面的方法来获取字段:

You could use something like the method below to get the field:

/// <summary>
/// Uses reflection to get the field value from an object.
/// </summary>
///
/// <param name="type">The instance type.</param>
/// <param name="instance">The instance object.</param>
/// <param name="fieldName">The field's name which is to be fetched.</param>
///
/// <returns>The field value from the object.</returns>
internal static object GetInstanceField(Type type, object instance, string fieldName)
{
    BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Static;
    FieldInfo field = type.GetField(fieldName, bindFlags);
    return field.GetValue(instance);
}

所以你可以这样称呼它:

So you could call this like:

string str = GetInstanceField(typeof(YourClass), instance, "someString") as string;

同样,这在大多数情况下不应该使用.

Again, this should not be used in most cases.

这篇关于如何使用反射获取私有字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆