使用Path语法取得对象的值

借鉴了http://stackoverflow.com/questions/4473928/c-sharp-dynamic-string-property-path

 

 

public class ReflectUtil
   {
       public static object ReflectOnPath(object o, string path)
       {
           object value = o;
           string[] pathComponents = path.Split(‘.‘);
           foreach (var component in pathComponents)
           {
               var x = component.Split(‘:‘);

               value = value.GetType().GetProperty(x[0]).GetValue(value, null);

               if (value.GetType().IsArray)
               {
                   int[] index = null;
                   if (x.Length > 1)
                       index = x.Skip(1).Take(int.MaxValue).Select(y => int.Parse(y)).ToArray();
                   if (index != null) value = ((Array)value).GetValue(index);
               }
           }
           return value;
       }
   }

 

 

 

Example:

[TestMethod]
       public void TestGetValue()
       {
           var o = new DistributeCfg
           {
               Configs = new[]
               {
                   new Config.Config
                   {
                       AppType = "v",
                       CallbackUrl = "fasdfasdf",
                       Key = "k",
                        NoticePostDataSetting = new PostDataSetting
                        {
                             Args = new Arg[]
                             {
                                  new Arg
                                  {
                                       Name = "name1",
                                       Value = "a.b.c"
                                  },
                                   new Arg
                                  {
                                       Name = "name2",
                                       Value = "a.b.c"
                                  }
                             }
                        },
                         PredictPostDataSetting  = new PostDataSetting
                        {
                             Args = new Arg[]
                             {
                                  new Arg
                                  {
                                       Name = "name1",
                                       Value = "Predict.b.c"
                                  },
                                  new Arg
                                  {
                                       Name = "name2",
                                       Value = "Predict.b.c"
                                  }
                             },
                              DeleteFlgSetting = new DeleteFlgSetting
                              {
                                   Audit = "1,2",
                                    Delete = "9",
                                     Pass = "10"
                              }
                        },
                   },
                     new Config.Config
                   {
                       AppType = "v",
                       CallbackUrl = "asdfasdfasdf",
                       Key = "k",
                        NoticePostDataSetting = new PostDataSetting
                        {
                             Args = new Arg[]
                             {
                                  new Arg
                                  {
                                       Name = "name1",
                                       Value = "a.b.c"
                                  },
                                   new Arg
                                  {
                                       Name = "name2",
                                       Value = "a.b.c"
                                  }
                             }
                        },
                         PredictPostDataSetting  = new PostDataSetting
                        {
                             Args = new Arg[]
                             {
                                  new Arg
                                  {
                                       Name = "name1",
                                       Value = "Predict.b.c"
                                  },
                                  new Arg
                                  {
                                       Name = "name2",
                                       Value = "Predict.b.c"
                                  }
                             },
                              DeleteFlgSetting = new DeleteFlgSetting
                              {
                                   Audit = "1,2",
                                    Delete = "9",
                                     Pass = "10"
                              }
                        },
                   }
               }
           };

           //var d = o.GetType().GetField("Configs").GetValue(o);

           string path = "Configs:0.PredictPostDataSetting.Args:0.Name";
           Console.WriteLine(ReflectUtil.ReflectOnPath(o, path));
           var p = o.GetType().GetProperty("Configs");
           //p.GetValue()
           //var array = o.GetType().GetProperty("Configs").GetType().IsArray;

           //var value = o.GetType().GetProperty("Configs").GetValue(o);

 

       }

       [TestMethod]
       public void TestValue()
       {
           var a = new A();
           a.Field = new B();
           a.Field.SubField = 10;

           string path = "Field.SubField";
           Console.WriteLine(ReflectUtil.ReflectOnPath(a, path));
       }

时间: 2024-11-08 19:10:17

使用Path语法取得对象的值的相关文章

笔记01 登录、常用配置参数、Action访问Servlet API 和设置Action中对象的值、命名空间和乱码处理、Action中包含多个方法如何调用

Struts2登录 1. 需要注意:Struts2需要运行在JRE1.5及以上版本 2. 在web.xml配置文件中,配置StrutsPrepareAndExecuteFilter或FilterDispatcher 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <filter>     <filter-name>struts2</filter-name>     <filter-class>org.apache.struts2.di

JavaScript强化教程——对象的值传递和引用传递

本文为 H5EDU 机构官方 HTML5培训 教程,主要介绍:JavaScript强化教程--对象的值传递和引用传递 function SetName(obj){  obj.name="Tom";//执行之前,此时的obj和Person的name属性均为undefined  obj1=new Object();  obj1=obj;//声明一个全局对象,那么obj.obj1和Person此时应该是同一个对象  }//SetName函数执行完之后,obj对象销毁,其余对象仍然存在  Pe

从头认识Spring-1.7 怎样通过属性注入Bean?(1)-怎样通过属性向对象注入值?

这一章节我们来讨论一下怎样通过属性注入Bean? 这一章节分为两部分,第一部分我们通过属性向对象注入值,第二部分我们通过属性向对象注入另一个对象的引用. 1.怎样通过属性向对象注入值? (1)domain package com.raylee.my_new_spring.my_new_spring.ch01.topic_1_7; public class Cake { private final int id = index++; private static int index = 0; pr

EF中修改对象的值的问题。。。(字段超级多的时候)

一般EF中修改单个对象的值,我是这样处理的. 如:DBEntities db=new DBEntities(); student stu = db.student.firstOrdefault(m=>m.id==id); stu.name="sb"; stu.age=11; ...... db.SaveChange(); 如果字段少的情况下,没什么问题(EF中好像还有一个修改的方法,先不管它). 如果200个字段呢?你还去一个个.属性么? 这个问题我用反射可以解决.具体方法见小弟

cocos3.0使用cocostudio动画帧结合地图对象键值创建精灵动画

内容如下: #include "cocos2d.h" #include "cocostudio/CocoStudio.h" //精灵猫和其他精灵的tag typedef enum{ catTag =1, }; //cocostudio 动画帧tag typedef enum{ catWalkTag = 1001, }; class Base :public cocos2d::Layer { public: Base(); ~Base(); //在地图中创建一个活多个

java使用反射比较两个bean对象属性值是否相等

import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; public class DomainEquals { /** * 日志操作类 */ private static Logger logger = Logger.getLogger(DomainEquals.c

从头认识Spring-2.6 在注解中使用表达式@Value(2)-使用表达式注入其他对象的值

这一章节我们来讨论一下在注解中使用表达式@Value,使用表达式注入其他对象的值. 1.domain 蛋糕类:只有一个public的名称 package com.raylee.my_new_spring.my_new_spring.ch02.topic_1_18; import org.springframework.beans.factory.annotation.Value; public class Cake { @Value("blueberry cheese cake") p

C#利用反射获取对象属性值

public static string GetObjectPropertyValue<T>(T t, string propertyname){     Type type = typeof(T); PropertyInfo property = type.GetProperty(propertyname); if (property == null) return string.Empty; object o = property.GetValue(t, null); if (o == n

[多线程系列]unsafe类和反射获取对象字段值速度比较

在分析atomic包的时候看到很多类的静态代码块中使用了一下这个方法(例如AtomicInteger) static { try { valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } 所以对objectFieldOffset方法很好奇,看了注释也没太了解,搜索了相