简体   繁体   中英

How do I get the type of a member through reflection?

I need to read the value of a member (it may be a field or a property) whose name is passed to my method. This is how I retrieve the MemberInfo:

MemberInfo member = itemType.GetField(fieldName) as MemberInfo ?? itemType.GetProperty(fieldName) as MemberInfo;

Next, I'd like to check the type of the member (field/property) that has been found. What's the correct way to do this?

You can use the PropertyType property of PropertyInfo or FieldType if FieldInfo

MemberInfo member = itemType.GetField(fieldName) as MemberInfo ?? itemType.GetProperty(fieldName) as MemberInfo;
Type type = member is PropertyInfo ? ((PropertyInfo)member).PropertyType : ((FieldInfo)member).FieldType;

Use MemberInfo.MemberType

var myProp = type.GetField(fieldName) ...;
var type = myProp.MemberType;

EDIT: To get the data-type of the property field you have also to distinguish between properties and fields:

var type = (myProp is PropertyInfo ?) 
    (pyProp as PropertyInfo).PropertyType) : 
    (myProp as FieldInfo).FieldType);

You can get this info from the FieldType and PropertyType properties of the field and property, respectively, but not (easily) from the MemberInfo itself. Here's one way you could write the code, that favors code clarity and not doing unnecessary tasks at run-time over code brevity.

void GetInfo(Type itemType, string fieldName) {
    FieldInfo field = itemType.GetField(fieldName);
    MemberInfo member;
    Type memberType;
    if (field != null) {
        member = field;
        memberType = field.FieldType;
    } else {
        PropertyInfo property = itemType.GetProperty(fieldName);
        if (property != null) {
            member = property;
            memberType = property.PropertyType;
        } else {
            member = null;
            memberType = null;
            // or throw an exception
        }
    }
    // do something with member and memberType
}

Note that if you only need memberType at the end, you can eliminate member entirely and make the code that much shorter.

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