C# 反射与特性结合筛选类属性
要将反射与特性结合使用并筛选出类中的属性,可以使用以下步骤:
- 创建一个自定义特性类,用于标识需要筛选的属性。例如:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class MyCustomAttribute : Attribute
{
// 可以在这里定义一些特性的属性
}
- 在需要筛选属性的类中,为需要筛选的属性添加自定义特性。例如:
public class MyClass
{
[MyCustom]
public int MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
[MyCustom]
public bool MyProperty3 { get; set; }
}
- 使用反射获取类中所有的属性,然后筛选出标记了自定义特性的属性。例如:
Type type = typeof(MyClass);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.GetCustomAttribute(typeof(MyCustomAttribute)) != null)
{
// 这里处理标记了自定义特性的属性
}
}
上述代码中,使用typeof(MyCustomAttribute)获取自定义特性的类型,然后使用GetCustomAttribute方法获取属性中标记了该特性的实例。如果获取到的实例不为空,则说明该属性标记了自定义特性,可以进行相应的处理。
原文地址: https://www.cveoy.top/t/topic/nsQT 著作权归作者所有。请勿转载和采集!