C#反射>嵌套属性getValue>对象与目标类型不匹配

时间:2014-12-14 08:53:40

标签: c# reflection attributes nested

我无法解决问题,所有值都在对象的第一级很好地重新获得,但嵌套属性值会生成错误。我确信我需要调整getValue参数对象,但我不确定如何。我试图传递nestedpropertyInfoArray,propertyInfo或req作为参数,但仍然是相同的错误。任何提示?

UpdatePhoneReq req = new UpdatePhoneReq();   
foreach (PropertyInfo propertyInfo in req.GetType().GetProperties())
{
    if (propertyInfo.CanRead)
    {
        string attributValue = "";
        string attributName = propertyInfo.Name;
        Type attributType = propertyInfo.PropertyType;
        if (attributType == typeof(XFkType))
        {
            PropertyInfo[] nestedpropertyInfoArray = propertyInfo.PropertyType.GetProperties();
            attributValue += "{";
            foreach (PropertyInfo subProperty in nestedpropertyInfoArray)
            {
                // --- > the GetValue below generates the error
                System.Diagnostics.Debug.WriteLine(subProperty.Name + "=" + subProperty.GetValue(req, null).ToString());
                attributValue += subProperty.Name + "=" + ",";

            }
            attributValue = attributValue.Substring(0, attributValue.Length - 1) + "}";
        }
        else
            attributValue = propertyInfo.GetValue(req, null) == null ? "" : propertyInfo.GetValue(req, null).ToString();

            System.Diagnostics.Debug.WriteLine("[" + propertyInfo.PropertyType + "]" + attributName + "=" + attributValue);
    }
}

1 个答案:

答案 0 :(得分:1)

您正在传递父对象" req"要获取子属性的值,您需要首先找到属性的值并传递它以获取子属性的值。

var propertyInfoValue = propertyInfo.GetValue(req, null);

然后将此propertyInfoValue用于subProperty

subProperty.GetValue(propertyInfoValue , null)