Find a private field with Reflection?

前端 未结 10 1381
自闭症患者
自闭症患者 2020-11-22 16:17

Given this class

class Foo
{
    // Want to find _bar with reflection
    [SomeAttribute]
    private string _bar;

    public string BigBar
    {
        ge         


        
10条回答
  •  渐次进展
    2020-11-22 16:48

    Nice Syntax With Extension Method

    You can access any private field of an arbitrary type with code like this:

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

    For that you need to define an extension method that will do the work for you:

    public static class ReflectionExtensions {
        public static T GetFieldValue(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);
        }
    }
    

提交回复
热议问题