我有一个包含数百个属性的类。每个属性都是用CategoryAttribute("My Category Name")属性子句声明的,这样它就可以很好地显示在PropertyGrid中。我想使用这个相同的CategoryAttribute属性来设置类中用特定categoryAttribute类别标记的所有属性的值。下面的代码可以编译并运行,但它没有完成任务,因为att_coll没有包含我期望的CategoryAttribute属性。有人知道怎么做吗?非常感谢。
class my_class
{
[CategoryAttribute("Category One")]
public int property_1
{
get { return _property_1; }
set { _property_1 = value; }
}
[CategoryAttribute("Category One")]
public int property_2
{
get { return _property_2; }
set { _property_2 = value; }
}
}
void ClearCatagory(string category_name)
{
CategoryAttribute target_attribute = new CategoryAttribute(category_name);
Type my_class_type = my_class.GetType();
PropertyInfo[] prop_info_array = my_class_type.GetProperties();
foreach (PropertyInfo prop_info in prop_info_array)
{
AttributeCollection att_coll = TypeDescriptor.GetAttributes(prop_info);
CategoryAttribute ca = (CategoryAttribute) att_col[typeof(CategoryAttribute)];
if (ca.Equals(target_attribute))
{
prop_info.SetValue(my_class, 0, null);
}
}
}发布于 2013-10-20 11:05:37
使用MemberInfo.GetCustomAttributes实例方法,而不是TypeDescriptor.GetAttriburtes。
调用应该是object[] attributes = prop_info.GetCustomAttributes(typeof(CategoryAttriute), false)。
或者,您可以使用TypeDescriptor.GetProperties而不是Type.GetProperties,您不应该在使用反射和TypeDescriptor之间切换。
此外,Category.Equals的documentation不是很清楚,但它很可能实现了引用相等(这是C#的默认设置,除非某个类特别覆盖了它)。这意味着无论Category的值是多少,只有当被比较的实例完全相同时,Equals才会返回true。如果是这种情况,那么ca.Equals(target_attribute)将始终为false,因为引用是不同的对象。
请尝试比较存储在Category值中的字符串值。字符串实现值相等,以便String.Equals比较存储在字符串中的值。
所以替换掉
if (ca.Equals(target_attribute))使用
if (ca.Cateogry.Equals(category_name))发布于 2013-10-21 09:00:17
非常感谢shf301解决了这个问题。以下是代码的工作版本:
class my_class
{
[CategoryAttribute("Category One")]
public int property_1
{
get { return _property_1; }
set { _property_1 = value; }
}
}
void ClearCatagory(string category_name)
{
Type my_class_type = my_class.GetType();
PropertyInfo[] prop_info_array = my_class_type.GetProperties();
foreach (PropertyInfo prop_info in prop_info_array)
{
CategoryAttribute[] attributes = (CategoryAttribute[]) prop_info.GetCustomAttributes(typeof(CategoryAttribute), false);
foreach(CategoryAttribute ca in attributes)
{
if (ca.Category == category_name)
{
prop_info.SetValue(my_class, 0, null);
}
}
}
}发布于 2017-12-23 16:44:48
public class cls
{
[Category("Default")]
[DisplayName("Street")]
public string Street { get; set; }
}
foreach (PropertyInfo propinf in cls.GetProperties())
{
var category = prop.CustomAttributes.Where(x => x.AttributeType ==typeof(CategoryAttribute)).First();
sCategory = category.ConstructorArguments[0].Value.ToString();
}这就是我们获得CustomAttribute价值的方法
https://stackoverflow.com/questions/19472912
复制相似问题