How to get the value of private field in C#?

后端 未结 8 1877
我在风中等你
我在风中等你 2020-11-29 06:55

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( stri         


        
相关标签:
8条回答
  • 2020-11-29 07:51

    Use reflections, but be prepared to be hit with a big stick from a fellow programmer.

    0 讨论(0)
  • 2020-11-29 07:52

    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.

    0 讨论(0)
提交回复
热议问题