是否有一种方法在类中“标记”一个属性,以便当我循环遍历类的属性时,我可以基于标记或未标记的属性执行一个方法。
我不能通过检查属性值来做到这一点。
测试类循环通过
public class SomeClass {
public List<Object> PropertyOne { get; set; }
public List<Object> PropertyTwo { get; set; }
public SomeClass() {
PropertyOne = new List<Object>();
PropertyTwo = new List<Object>();
}
}阅读特性:
SomeClass myObject = new SomeClass();
Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
// If this prop is "marked" -> Execute code below
}编辑:谢谢你们给出了很好的答案。
发布于 2014-11-20 10:03:01
这就是属性的意义所在。创建自己的属性,将其应用于属性并测试prop.GetCustomAttribute<MyMarkerAttribute>()不是null。
public class MyMarkerAttribute : Attribute
{
}
public class SomeClass
{
// unmarked
public List<Object> PropertyOne { get; set; }
[MyMarkerAttribute] // marked
public List<Object> PropertyTwo { get; set; }
}
foreach (PropertyInfo prop in props)
{
if (prop.GetCustomAttribute<MyMarkerAttribute>() != null)
{
// ...
}
}发布于 2014-11-20 10:04:17
您可以为此使用属性。
public class MyAttribute : Attribute
{
}
public class SomeClass {
[MyAttribute]
public List<Object> PropertyOne { get; set; }
public List<Object> PropertyTwo { get; set; }
public SomeClass() {
PropertyOne = new List<Object>();
PropertyTwo = new List<Object>();
}
}然后在迭代属性时检查属性,如下所述:如何从代码中检索数据注释?(以编程方式)
public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
return (T)property .GetCustomAttributes(attrType, false).FirstOrDefault();
}https://stackoverflow.com/questions/27036693
复制相似问题