[原 -> 磚] C# IEnumerable 泛型取值


為什么要寫這個?因為發現,很多人在讀取泛型集合中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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM