如何让私人领域在C#中的价值? [英] How to get the value of private field in C#?

查看:191
本文介绍了如何让私人领域在C#中的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了,我需要访问类的私有领域的问题。例如:

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;
    }
}

如何才能someString的价值MyClass的外?

How can I get the value of someString outside MyClass ?

对不起,我不能在这里,因为实际生产code为保护财产使用。我是QA /开发,我需要一种方式来获得用于编写用户验收测试这些保密。因此,我不能改变生产code。你能帮我吗?

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?

推荐答案

正如其他人所说,因为字段是私有的,你不应该试图与正常code得到它。
这是可以接受的唯一情况是单元测试过程中,即使如此,你需要一个很好的理由这样做(如设置私有变量为空,这样code在异常块将受到重创,并且可以测试)。

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.

这篇关于如何让私人领域在C#中的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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