[原 -> 砖] 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);

 

转载于:https://www.cnblogs.com/goldli/p/4516467.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值