简体   繁体   中英

C# get fields with reflection

In C# how do you use reflection to get variables that doesn't have getters/setters? For example the getValue method below will work for d2, but not d1.

public class Foo {

    public String d1;
    public String d2 { get; set; }

    public object getValue(String propertyName){
        return this.GetType().GetProperty(propertyName).GetValue(this, null);
    }
}

d1 is not a property. It is a field. Use the reflection methods for Fields instead.

public class Foo {

    public String d1;
    public String d2 { get; set; }

    public object getValue(String propertyName){
        var member = this.GetType().GetMember(propertyName).Single();
        if (member is PropertyInfo)
        {
            return ((PropertyInfo)member).GetValue(this, null);
        }
        else if (member is FieldInfo)
        {
            return ((FieldInfo)member).GetValue(this);
        }
        else throw new ArgumentOutOfRangeException();
    }
}

d1 is not a property. It's a field. You would use this.GetType().GetField to retrieve it via reflection.

public object getFieldValue(String fieldName){
    return this.GetType().GetField(fieldName).GetValue(this);
}

What you are probably trying to is make getValue return the value of a property or field. You can use GetMember can tell you if it is a property or a field. For example:

public object getValue(String memberName) {
    var member = this.GetType().GetMember(memberName).Single();
    if (member.MemberType == MemberTypes.Property) {
         return ((PropertyInfo)member).GetValue(this, null);
    }
    if (member.MemberType == MemberTypes.Field) {
        return ((FieldInfo)member).GetValue(this);
    }
    else
    {
        throw new Exception("Bad member type.");
    }
}

You have to use the GetField method.

Msdn: Type.GetField()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM