类的一个属性更改的时候怎么把这个类的另外一个属性[Browsable(true)]更改?

lg314 2010-08-20 01:55:23
    class Item
{
public int ItemType
{
get;
set;
}
[Browsable(true)]
public string ItemName
{
get;
set;
}
}


比如说 ItemType==0 的时候[Browsable(false)] ItemName
...全文
265 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lg314 2010-08-20
  • 打赏
  • 举报
回复
呵呵,高手啊,谢谢
wuyq11 2010-08-20
  • 打赏
  • 举报
回复
public void SetPropertyVisibility(object obj, string propertyName, bool visible)
{
Type type = typeof(BrowsableAttribute);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
AttributeCollection attrs = props(propertyName).Attributes;
FieldInfo fld = type.GetField("browsable ", BindingFlags.Instance | BindingFlags.NonPublic);
fld.SetValue(attrs(type), visible);
}
zjx198934 2010-08-20
  • 打赏
  • 举报
回复
学习了!
zhengqian529 2010-08-20
  • 打赏
  • 举报
回复
忘记告诉你,别忘记引用

using System.ComponentModel;
using System.Reflection;
zhengqian529 2010-08-20
  • 打赏
  • 举报
回复
LZ是要更改属性吧?
我给你2个方法,第一个,用于更改一个属性的IsReadOnly属性,比如你添加了[IsReadOnly(True)]

private void SetPropertyReadOnly(object obj, string propertyName, bool readOnly)
{
try
{
Type type = typeof(ReadOnlyAttribute);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
AttributeCollection attrs = props[propertyName].Attributes;
FieldInfo fld = type.GetField("isReadOnly", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance);
fld.SetValue(attrs[type], readOnly);
}
catch (Exception ex)
{
SATLogger.LogException(ex);
}
}


第二个解决你Browsable的问题

private void SetPropertyVisibility(object obj, string propertyName, bool visible)
{
try
{
Type type = typeof(BrowsableAttribute);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
AttributeCollection attrs = props[propertyName].Attributes;
FieldInfo fld = type.GetField("browsable", BindingFlags.Instance | BindingFlags.NonPublic);
fld.SetValue(attrs[type], visible);
}
catch (Exception ex)
{
SATLogger.LogException(ex);
}
}


调用方法:

//rule 是你的属性的归属对象的实例,它是object类型,你的类型是什么你自己应该知道吧
//"ExcludeList" 属性的名称,在你这里应该是"ItemName"
//第三个参数指定你要改变为何值,这里是true or false
SetPropertyVisibility(rule, "ExcludeList", true);


应该说明清楚了
g394594141 2010-08-20
  • 打赏
  • 举报
回复
请参看我的博客
http://blog.csdn.net/g394594141/archive/2010/04/27/5535301.aspx
  • 打赏
  • 举报
回复
写个基类应用特性,派生类使用时再改变
个人愚见

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧