Best way to get sub properties using GetProperty

后端 未结 6 672
南方客
南方客 2020-12-08 10:21
public class Address
{
    public string ZipCode {get; set;}
}

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

how can I access e

6条回答
  •  天命终不由人
    2020-12-08 11:03

    Problem: Weakly Typed Variables:

    @jonskeet's FollowPropertyPath(...) method almost met my needs exactly; except that my property was weakly typed; therefore, currentType = property.PropertyType simply returned System.Object and failed on the next iteration of the foreach-loop.

    Solution: To use the runtime type rather than the design-time type, I adjusted the method as follows:

    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 = value.GetType();    // <-- Change
        }
        return value;
    }
    

提交回复
热议问题