读匿名object对象的属性值

读匿名object对象的属性值


1、定义读object对象值的功能方法

public static class StaticClass
{
    public static string ValueByKey(this object obj,string key)
    {
        Type type = obj.GetType();
        //可以通过GetProperty取得对象指定的属性信息
        PropertyInfo info = type.GetProperty("属性名");
        PropertyInfo[] ps = type.GetProperties();
        Dictionary<string, string> dic = new Dictionary<string, string>();
        foreach (PropertyInfo p in ps)
        {            
            var n = p.Name;
            //可以通过SetValue设置对象的属性值
            //p.SetValue("属性名", "属性值",null);
            var v = p.GetValue(obj, null);
            var t = p.PropertyType;
            if (n != null && v != null)
                dic.Add(n.ToString(), v.ToString());
        }
        return dic[key];
    }
}

  

2、调用

string value = new { id = 1, title = "标题" }.GetValue("id");   //结果:1      正确

  

判断为值类型还是对象类型

Object obj = "我是值类型";
if (obj.GetType().IsValueType)
    Console.WriteLine( "类型:" + obj + "为值类型");
else
    Console.WriteLine( "类型:" +obj + "为引用类型");

判断对象是否为Dictionary类型

如果知道Dictionary的类型T1, T2,就可以直接使用下面的方式
if (obj is Dictionary<T1, T2>)

  

原文地址:https://www.cnblogs.com/sntetwt/p/5356808.html