C#读取匿名对象
通过new出匿名对象,可以直接调用该匿名对象的属性名,获取属性值。
var objUser = new {Name="Lilei",Age=18 }; //此时可直接读取匿名类属性 Console.WriteLine("Name:" + objUser.Name);// Name:Lilei
但当将匿名对象转换成object后,就无法直接读取属性值了;
static object GetObj() { var obj = new { Name = "Lilei", Age = 18 }; return obj; } static void Main(string[] args) { var obj = GetObj();//此时已无法通过obj.Name的方式获取属性值了 }
1、通过反射的方式获取属性值
static object GetObj() { var obj = new { Name = "Lilei", Age = 18 }; return obj; } static void Main(string[] args) { var obj = GetObj(); //此时可通过反射的方式获取属性值 string objName = obj.GetType().GetProperty("Name").GetValue(obj).ToString(); Console.WriteLine(objName);// Lilei }
var Data = this.GetWorkHours(QueryDto); var Result = Data.GetType().GetProperty("Result").GetValue(Data); // 反射获取获取 Result var dtoList = Result.GetType().GetProperty("dtoList").GetValue(Result); //再通过Result获取dtoList
2、新建个扩展方法,将object转成对应的匿名对象
class Program { static void Main(string[] args) { var obj = GetObj(); var user = obj.ObjCast(new { Name = "", Age = 0 }); Console.WriteLine("Name:{0},Age:{1}", user.Name, user.Age);// Name:Lilei,Age:18 var objList = GetObjList(); var userList = objList.Select(p => p.ObjCast(new { Name = "", Age = 0 })).ToList(); userList.ForEach(p => { Console.WriteLine("Name:{0},Age:{1}", p.Name, p.Age); }); // Name:Lilei,Age:18 // Name:HanMeimei,Age:20 } static object GetObj() { var obj = new { Name = "Lilei", Age = 18 }; return obj; } static List<object> GetObjList() { List<object> objList = new List<object>(); objList.Add(new { Name = "Lilei", Age = 18 }); objList.Add(new { Name = "HanMeimei", Age = 20 }); return objList; } } static class Extensions { public static T ObjCast<T>(this object obj, T sample) { return (T)obj; } }
原文:https://www.cnblogs.com/willingtolove/p/11204018.html