动态修改DisplayName已经实现(参考http://blog.csdn.net/luyifeiniu/article/details/5426960),但是Category 和Description无法实现,我仿照他(她)得最后哪两段代码写了如下代码
/// <summary> /// 设置属性要显示的描述 /// </summary> /// <param name="obj">属性所属的类</param> /// <param name="propertyName">属性</param> /// <param name="value">描述</param> public static void SetPropertyDescription(ref object obj, string propertyName, string value) { Type type = typeof(System.ComponentModel.DescriptionAttribute); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj); AttributeCollection attrs = props[propertyName].Attributes; FieldInfo fld = type.GetField("description", BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); fld.SetValue(attrs[type], value); } /// <summary> /// 设置属性的分类依据 /// </summary> /// <param name="obj">属性所属的类</param> /// <param name="propertyName">属性</param> /// <param name="value">名称</param> public static void SetPropertyCategory(object obj, string propertyName, string value) { Type type = typeof(System.ComponentModel.CategoryAttribute); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj); AttributeCollection attrs = props[propertyName].Attributes; FieldInfo fld = type.GetField("CategoryValue", BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); fld.SetValue(attrs[type], value); }
代码运行不报错,,但是只会显示修改前的值,,求大虾帮忙如何实现修改动态修改Category 和Description