Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c# - Best way to get sub properties using GetProperty

public class Address
{
    public string ZipCode {get; set;}
}

public class Customer
{
    public Address Address {get; set;}
}

how can I access eitther "ZipCode" or "Address.ZipCode" with reflection? For example:

Typeof(Customer).GetProperty("ZipCode")?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'd need something like:

PropertyInfo addressProperty = typeof(Customer).GetProperty("Address");
ProportyInfo zipCodeProperty = addressProperty.PropertyType.GetProperty("ZipCode");

object address = addressProperty.GetValue(customer, null);
object zipCode = zipCodeProperty.GetValue(address, null);

Basically if you want to take a string "Address.ZipCode" and navigate down it, you need to split it by "." and then call GetProperty on the appropriate type at every step to get the property itself, then PropertyInfo.GetValue to get the next value in the chain. Something like this:

public static object FollowPropertyPath(object value, string path)
{
    Type currentType = value.GetType();

    foreach (string propertyName in path.Split('.'))
    {
        PropertyInfo property = currentType.GetProperty(propertyName);
        value = property.GetValue(value, null);
        currentType = property.PropertyType;
    }
    return value;
}

Call it like this:

object zipCode = FollowPropertyPath(customer, "Address.ZipCode");

Note that this works on the compile-time types of the properties. If you want it to cope with the execution time type (e.g. if customer.Address didn't have a ZipCode property, but the actual type returned by Address did) then change property.PropertyType to property.GetType().

Also note that this doesn't have any error handling etc :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...