有没有办法在类中“标记”一个属性,这样当我遍历类的属性时,我可以执行一个方法,基于标记或未标记的属性。
我无法通过检查属性值来执行此操作。
测试类循环
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
}
编辑: 谢谢你们两位大家的答案。
答案 0 :(得分:1)
这就是属性的用途。 Create your own attribute,将其应用于属性并测试prop.GetCustomAttribute<MyMarkerAttribute>()
不为空。
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)
{
// ...
}
}
答案 1 :(得分:1)
您可以使用属性
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>();
}
}
然后在迭代属性时检查属性,如下所述:How to retrieve Data Annotations from code? (programmatically)
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();
}