C# 类的属性想添加Caption属性。怎么通过反射检查某个对象的某个属性是否定义了Caption属性。
可以使用反射中的 GetCustomAttributes 方法来检查某个属性是否定义了Caption属性,示例如下:
// 定义一个带有Caption特性的属性
class MyProperty
{
[Caption("属性名称")]
public string Name { get; set; }
}
// 定义Caption特性
[AttributeUsage(AttributeTargets.Property)]
class CaptionAttribute : Attribute
{
public string Caption { get; }
public CaptionAttribute(string caption)
{
Caption = caption;
}
}
// 检查某个对象的某个属性是否定义了Caption属性
var myProperty = new MyProperty();
var propertyInfo = myProperty.GetType().GetProperty("Name");
var captionAttribute = propertyInfo.GetCustomAttributes(typeof(CaptionAttribute), false).FirstOrDefault() as CaptionAttribute;
if (captionAttribute != null)
{
Console.WriteLine($"属性名:{propertyInfo.Name},属性值:{captionAttribute.Caption}");
}
else
{
Console.WriteLine($"属性名:{propertyInfo.Name}");
}
在上述代码中,我们定义了一个带有Caption特性的属性 MyProperty.Name,并定义了 CaptionAttribute 类来表示 Caption 特性。然后使用反射获取属性信息,再使用 GetCustomAttributes 方法来获取该属性的所有特性,并使用 FirstOrDefault 方法获取第一个 CaptionAttribute 特性,最后输出属性名和属性值。如果该属性没有定义 Caption 特性,则只输出属性名。
原文地址: https://www.cveoy.top/t/topic/bqeO 著作权归作者所有。请勿转载和采集!