• [原 -> 砖] C# IEnumerable<T>泛型取值


    为什么要写这个?因为发现,很多人在读取泛型集合中Item的值时,使用的方法是 item.GetType().GetField("xxxxx").GetValue() 或类似的写法。看到这种写法,我就知道,那个Coder一定不是很熟悉对象的内存分配,所以纠正一下写法。顺便说下这样写的依据。

    首先是对象在内存的存放方式。也就是C#(或者其它语言)数据类型分为基础数据类型与引用数据类型的原因。

    基础数据类型在内存中是值型的。用教我编程入门的老师的比方就是: 对象就像一幢楼。基础数据(值)类型就是一个个的房间(假设房间是最小单位)。引用数据类型就房间号索引;在内存中的表现为地址偏移量。那么,要去哪个房间,只需要检索房间号就可以了。

    所以,当你取道了T的指定field时,就知道了field相对于T的基址的偏移量。那么,实例的基址(内存地址) + 偏移量,就可以得到你想要的值。

    public static class Helper
        {
            public static string To<T>(this IEnumerable<T> source, string field, Type type)
            {
                var t = typeof (T);
                var result = "";
                if (type == typeof(PropertyInfo))
                {
                    var p = t.GetProperty(field);
                    if (p != null)
                    {
                        foreach (var item in source)
                        {
                            result += p.GetValue(item,null) + ",";
                        }                   
                    }
                }
                else if (type == typeof(FieldInfo))
                {
                    var f = t.GetField(field);
                    if (f != null)
                    {
                        foreach (var item in source)
                        {
                            result += f.GetValue(item) + ",";
                        }                   
                    }
                }
                return result;
            }
        }

    用例:

        public class Ax
        {
            public string Value;
            private string Name;
            public int Age { get; set; }
        }
                var list = new List<Ax>
                {
                    new Ax {Age = 30, Value = "goldli"},
                    new Ax {Age = 35, Value = "金利"}
                };
    
                var x = list.To("Age",typeof(PropertyInfo));
                Debug.WriteLine(x);
  • 相关阅读:
    with一个对象,自动触发__enter__方法
    SQLAlchemy-Utils
    SQLAlchemy
    wtforms
    Python数据库连接池DBUtils(基于pymysql模块连接数据库)
    VMWare安装linux centos,安装中文输入法
    HttpServletRequest和ServletRequest的区别
    Java序列化
    mybatis循环取序列,值相同问题处理
    利用jdk将wsdl生成java代码
  • 原文地址:https://www.cnblogs.com/goldli/p/4516467.html
Copyright © 2020-2023  润新知