zoukankan      html  css  js  c++  java
  • [原 -> 砖] 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);
  • 相关阅读:
    判断一个值是不是数字
    webpack起的项目怎么用手机访问?
    vue 父子组件数据双向绑定
    js取整
    封装加减乘除函数 解决JS 浮点数计算 Bug
    javascript笔记 (持续更新)
    ajax请求的原生js实现
    程序员の健康和效率装备列表,普通人也能参考
    Java static,final 基本概念
    Download EditPlus Text Editor
  • 原文地址:https://www.cnblogs.com/goldli/p/4516467.html
Copyright © 2011-2022 走看看