如何获得嵌套类的一个值以及主类。 [英] How to get value of one the of the nested class along with main class.

查看:69
本文介绍了如何获得嵌套类的一个值以及主类。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have nested class which has two properties. 
I need to get value of one the of the nested class along with main class.

		foreach (var row in reportRowList)
            {
                var k = row;
                List<object> dataRow = new List<object>();
                properties.ForEach(p =>
                {

                    dataRow.Add(p.GetValue(row));
                   
                });

                table.Rows.Add(dataRow.ToArray());
            }
			
			Below is my code. How do i extend GetValue Method of PropertyInfo to retrieve nested object properties 





我尝试过:





What I have tried:

public static Object GetPropValue(this Object obj, String propName)
       {
           string[] nameParts = propName.Split('.');
           if (nameParts.Length == 1)
           {
               return obj.GetType().GetProperty(propName).GetValue(obj, null);
           }

           foreach (String part in nameParts)
           {
               if (obj == null) { return null; }

               Type type = obj.GetType();
               PropertyInfo info = type.GetProperty(part);
               if (info == null) { return null; }

               obj = info.GetValue(obj, null);
           }
           return obj;
       }

推荐答案

obj = info.GetValue(obj, null);





此时,您调用GetPropValue()来获取嵌套类属性;保证,当然,在这种情况下你只能潜入1个额外的级别。



如何为嵌套类提供目标属性是另一回事:2个列表/ strings?



At this point, you call GetPropValue() to get the "nested class properties"; insuring, of course, you only "dive down" 1 extra level in this case.

How you supply your target properties for the nested class is another matter: 2 lists / strings?


这篇关于如何获得嵌套类的一个值以及主类。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆