有一个类里有一个property,设定其有一个Atrribute如下:
        [CategoryAttribute("激光传输强度(mw)")]
        public int LaserTransmission
        {
            get { return laser_transmission; }
            set { laser_transmission = value; }
        }根据如下方法获取其值
string propertyname = property.GetCustomAttributesData()[0].ConstructorArguments[0].Value.ToString();对应上述property的propertyname="激光传输强度(mw)",请问各路高手,能利用这个propertyname反过来找到这个property,即LaserTransmission吗?

解决方案 »

  1.   


    //参考
     Type t = typeof(A);
                foreach (PropertyInfo pi in t.GetProperties())
                {
                    foreach (CategoryAttribute attr in pi.GetCustomAttributes(typeof(CategoryAttribute), false))
                    {
                        if (attr.Category=="haha")
                        {
                            MessageBox.Show(pi.Name);
                        }
                    }
                }
      

  2.   

    PropertyInfo[] peroperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo property in peroperties)
            {
                object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objs.Length > 0)
                {
                    Console.WriteLine("{0}: {1}", property.Name, ((DescriptionAttribute)objs[0]).Description);
                }
            }
            Console.ReadKey();
      

  3.   

                var c = new TestClass() { LaserTransmission = 867 };            var prop = c.GetType().GetProperties().FirstOrDefault(p =>
                {
                    var attrs = p.GetCustomAttributes(typeof(CategoryAttribute), false);
                    if (attrs != null && attrs.Length > 0)
                    {
                        foreach (var attr in attrs)
                        {
                            if (((CategoryAttribute)attr).Category.Equals("激光传输强度(mw)"))
                            {
                                return true;
                            }
                        }
                    }
                    return false;
                });            if (prop != null)
                {
                    var value = prop.GetGetMethod().Invoke(c, null);
                    Console.WriteLine(value);
                }