How to set Vaues to the Nested Property using C# Reflection.?

ぃ、小莉子 提交于 2019-11-28 18:49:28

You should be calling PropertyInfo.GetValue using the Country property to get the country, then PropertyInfo.SetValue using the Id property to set the ID on the country.

So something like this:

public void SetProperty(string compoundProperty, object target, object value)
{
    string[] bits = compoundProperty.Split('.');
    for (int i = 0; i < bits.Length - 1; i++)
    {
        PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]);
        target = propertyToGet.GetValue(target, null);
    }
    PropertyInfo propertyToSet = target.GetType().GetProperty(bits.Last());
    propertyToSet.SetValue(target, value, null);
}
Mohamed.Abdo

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]);
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!