[Reflection]簡單的C# Reflection練習

  • 5185
  • 0
  • C#
  • 2018-04-08

其實Reflection不難  但就是效能比不上hard code好

如果應用的情境不需在意效能 拿來處理一些瑣碎的小功能是蠻好用的

今天我們以假設要輸入一個字串List => 取回 不重覆、並排除空字串、Null、前後空白為例

來寫一個小function

 

例如

我們輸入了四個元素

但其實不重覆、並排除空字串、Null、前後空白後 只會得到一個A而已

namespace MySample.Console
{
    class Program
    {
        class Sample
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        static void Main(string[] args)
        {
            var data = new List<Sample>
            {
                new Sample { Id = 1, Name = "A" },
                new Sample { Id = 2, Name = "      A      " },
                new Sample { Id = 3, Name = null },
                new Sample { Id = 3, Name = "   " },
            };

            var result = GetPureStrList(data, "Name");
        }

        /// <summary>
        /// 取不重覆的 String List (並排除空字串、Null、前後空白)
        /// </summary>
        private static List<string> GetPureStrList<T>(IEnumerable<T> obj, string name)
        {
            var result = new List<string>();
            var target = typeof(T).GetProperties().Where(q => q.Name == name);

            //根本找不到這個欄位
            if (!target.Any())
            {
                throw new Exception("找不到");
            }
            else
            {
                var propertyInfo = target.First();
                foreach (var item in (IEnumerable)obj)
                {
                    var value = propertyInfo.GetValue(item, null);
                    if (value == null)
                    {
                        continue;
                    }
                    else
                    {
                        result.Add(value.ToString());
                    }
                }
            }

            return result.Where(q => !String.IsNullOrWhiteSpace(q)).Select(q => q.Trim()).Distinct().ToList();
        }
    }
}