跳转至

Attribute —— 特性

特性是一种特殊类型的数据成员,它为程序元素(如类、方法、属性等)提供元数据,即描述数据的数据。特性可以用于在运行时获取有关程序元素的信息,或者控制程序元素的某些行为。

在C#中,特性以[特性名]的形式使用,可以应用于类、方法、属性等程序元素。特性可以包含参数,用于传递额外的信息。

下面是一个简单的示例,演示了如何定义特性:

//这个是声明在属性上的一个特性,这个特性可以用于描述属性的信息
//操作和平常的类类似,只是多了一个Attribute后缀
[AttributeUsage(AttributeTargets.Property)]
public class InfoAttribute : Attribute
{
    public string value { get; set; }
    public InfoAttribute(string content)
    {
        value = content;
    }
    ///<summary>
    /// 获取特性中的值
    /// </summary>
    public static string GetInfoAttributeValue(PropertyInfo propertyInfo)
    {
        InfoAttribute infoAttribute = propertyInfo.GetCustomAttribute<InfoAttribute>();
        return infoAttribute.value;
    }
}

使用:在这个类的属性上面声明了一些信息。

public class CompareItem
{
    [InfoAttribute("层名")]
    public string markerName { get; set; }
    [InfoAttribute("实钻井顶深")]
    public string markerStartDepth_ing { get; set; }
    [InfoAttribute("实钻井低深")]
    public string markerEndDepth_ing { get; set; }
    [InfoAttribute("参考井顶深")]
    public string markerStartDepth_ed { get; set; }
    [InfoAttribute("参考井低深")]
    public string markerEndDepth_ed { get; set; }
}

个人感觉一般是通过反射来进行调用 可用于动态创建数据,例如在创建DataTable时,可以通过反射将属性的名称作为列的ColumnName,特性中的信息可以作为列的Caption。就不需要手动指定对应关系,能够复用。例如:

DataTable dt = new DataTable();
foreach (var item in typeof(CompareItem).GetProperties())
{
    var attr = item.GetCustomAttribute<InfoAttribute>();
    if (attr != null)
    {
        dt.Columns.Add(new DataColumn(item.Name, item.PropertyType) { Caption = attr.value });
    }
}