C# 匿名对象随笔

  

 

C#中匿名对象的一般写法是这样的:

object o=new {Name="TestName"};


有时候我们会尝试从这个匿名对象中获取值,在使用中发现例如已知类型的对象如T model,

下面的代码是没有问题的:

           object value = null;
            Type objType = typeof(T);
            var propertInfo = objType.GetProperty(propertyName);
            if (propertInfo != null)
            {
                value = propertInfo.GetValue(model, null);
            }

但是对于匿名对象,该代码失效,原因就在于匿名对象没有自己具体的类型,所有typeof取到
的类型里将会找不到该属性(Name),因为无法获取他的值。更为普遍的兼容做法是使用实例

的GetType()方法:

           object value = null;
            Type objType = model.GetType();
            var propertInfo = objType.GetProperty(propertyName);
            if (propertInfo != null)
            {
                value = propertInfo.GetValue(model, null);
            }

这样,不管是匿名对象还是自定义(已知类型)对象的属性值都可以获取到了。

posted @ 2014-05-22 13:49  ____轨迹  阅读(5478)  评论(0编辑  收藏  举报