如何使用C#Reflection将Vaues设置为嵌套属性.?

Sra*_*van 20 c# reflection propertyinfo

我试图使用反射动态地将值设置为类的嵌套属性.任何人都可以帮我这样做.

我正在上课Region.

public class Region
{
    public int id;
    public string name;
    public Country CountryInfo;
}

public class Country
{
    public int id;
    public string name;
}
Run Code Online (Sandbox Code Playgroud)

我有一个Oracle数据阅读器来提供Ref游标中的值.

这会给我一个

ID,姓名,COUNTRY_ID,COUNTRY_NAME

我可以通过下面的方式将值分配给Region.Id,Region.Name.

FieldName="id"
prop = objItem.GetType().GetProperty(FieldName, BindingFlags.Public | BindingFlags.Instance);
prop.SetValue(objItem, Utility.ToLong(reader_new[ResultName]), null);
Run Code Online (Sandbox Code Playgroud)

对于嵌套属性,我可以通过读取Fieldname创建实例来为下面的值赋值.

FieldName="CountryInfo.id"

if (FieldName.Contains('.'))
{
    Object NestedObject = objItem.GetType().GetProperty(Utility.Trim(FieldName.Split('.')[0]), BindingFlags.Public | BindingFlags.Instance);

    //getting the Type of NestedObject
    Type NestedObjectType = NestedObject.GetType();

    //Creating Instance
    Object Nested = Activator.CreateInstance(typeNew);

    //Getting the nested Property
    PropertyInfo nestedpropinfo = objItem.GetType().GetProperty(Utility.Trim(FieldName.Split('.')[0]), BindingFlags.Public | BindingFlags.Instance);

    PropertyInfo[] nestedpropertyInfoArray = nestedpropinfo.PropertyType.GetProperties();
    prop = nestedpropertyInfoArray.Where(p => p.Name == Utility.Trim(FieldName.Split('.')[1])).SingleOrDefault();

    prop.SetValue(Nested, Utility.ToLong(reader_new[ResultName]), null);
    Nestedprop = objItem.GetType().GetProperty(Utility.Trim(FieldName.Split('.')[0]), BindingFlags.Public | BindingFlags.Instance);

    Nestedprop.SetValue(objItem, Nested, null);
}
Run Code Online (Sandbox Code Playgroud)

以上赋值给Country.Id.

但是,因为我每次都创建实例,所以Country.Id如果我去Next Country.Name,我就无法获得之前的值.

有谁可以告诉分配值的objItem(that is Region).Country.IdobjItem.Country.Name.这意味着如何将值分配给嵌套属性,而不是每次创建实例和分配.

提前致谢.!

Jon*_*eet 51

您应该PropertyInfo.GetValue使用该Country属性来调用该国家/地区,然后PropertyInfo.SetValue使用该Id属性在该国家/地区设置 ID.

所以像这样:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 因为这不是教程.这个答案简短而又甜蜜,只包含必要的代码.您有责任根据自己的要求添加检查/异常处理.代码工作得很好btw. (6认同)
  • 为什么这被接受为答案,它会抛出一个 nullref,因为如果目标尚未实例化,GetValue() 将返回 null,这将进一步导致异常。 (2认同)