How do I get any object and its private field read and then returned
public class Person
{
private string _password;
}
public string Name { get; set }
public Gender man { get; set }
public int Age { get; set }
}
Here is the class from which you have to get the data
It's pretty simple. You need to get the type of your target object with typeof
or GetType()
if you have an instance like in this case. Then you can use GetField
to get the desired field. But there is a catch. GetField
by default only search for fields that are public and non-static. TO chage that you need to give it some BindingFlags
. An Example:
public static string ReadPrivateField(object obj, string fieldName)
{
var type = obj.GetType();
// NonPublic = obly search for private fields.
// Instance = only search for non-static fields.
var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
return field.GetValue(obj) as string;
}