首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

为啥GetProperty()获取不了属性

2013-09-07 
为什么GetProperty()获取不了属性我不太懂反射原理,只知道这几个方法。平常使用的时候,GetProperty()都能获

为什么GetProperty()获取不了属性
我不太懂反射原理,只知道这几个方法。
平常使用的时候,GetProperty()都能获取值。
但是linq得到的对象IEnumerable<T>就取不到了

如果IEnumerable<T>.GetProperties()就可以把所有值都取出来
但是IEnumerable<T>.GetProperty(name)就永远是null

怎么办呀


        public static string ContactText<T>(this IEnumerable<T> en, string name, string separator)
        {
            string result = string.Empty;

            if (en is Array)
            {
                result = ContactEnumerable(en, null, separator);
            }
            else
            {
                result = ContactEnumerable(en, name, separator);
            }
            if (result.Contains(separator))
                result = result.Substring(separator.Length);
            return result;
        }

        public static string ContactEnumerable<T>(IEnumerable<T> en, string name, string separator)
        {
            System.Reflection.PropertyInfo pi = null;
            StringBuilder sb = new StringBuilder();

            if (name == null)
            {
                foreach (object o in en)
                    sb.Append(string.Concat(separator, o));
            }


            else
            {
                foreach (var v in en)
                {
                    pi = en.GetType().GetProperty(name);//取不到值
                    System.Reflection.PropertyInfo[] pis = v.GetType().GetProperties();//能取到所有的属性
                    System.Windows.Forms.Button btn = new System.Windows.Forms.Button();
                    pi = btn.GetType().GetProperty("Text");
                    break;
                }

                if (pi != null)
                {
                    foreach (var v in en)
                    {
                        object o = pi.GetValue(v, null);
                        if (o == null)
                            o = string.Empty;
                        sb.Append(string.Concat(separator, o.ToString()));
                    }
                }
            }


            return sb.ToString();
        }



我要取出特定的值我该怎么办呀?
谢谢各位大侠。
[解决办法]
 pi = v.GetType().GetProperty(name);//取不到值

热点排行