Getting Nested Object Property Value Using Reflection

前端 未结 11 2006
甜味超标
甜味超标 2020-12-03 06:55

I have the following two classes:

public class Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public         


        
11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 07:50

    Get Nest properties e.g., Developer.Project.Name

    private static System.Reflection.PropertyInfo GetProperty(object t, string PropertName)
                {
                    if (t.GetType().GetProperties().Count(p => p.Name == PropertName.Split('.')[0]) == 0)
                        throw new ArgumentNullException(string.Format("Property {0}, is not exists in object {1}", PropertName, t.ToString()));
                    if (PropertName.Split('.').Length == 1)
                        return t.GetType().GetProperty(PropertName);
                    else
                        return GetProperty(t.GetType().GetProperty(PropertName.Split('.')[0]).GetValue(t, null), PropertName.Split('.')[1]);
                }
    

提交回复
热议问题