zoukankan      html  css  js  c++  java
  • 读匿名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>)
    

      

  • 相关阅读:
    HTML: vertical algin Big/small div in same row (bootstrap)
    unix时间转换
    chrome工具分析
    DNF 包管理器
    安装nodejs
    location属性解释
    angular深入理解途径
    ui-router与ngRoute
    angular $location服务获取url
    Python文件操作
  • 原文地址:https://www.cnblogs.com/sntetwt/p/5356808.html
Copyright © 2011-2022 走看看