C# 自定义特性

摘要


C# 可通过定义特性类创建自己的自定义特性,特性类是直接或间接派生自 Attribute 的类,可快速轻松地识别元数据中的特性定义。假设我们希望使用编写类的程序员名字来标记该类,那么我们就需要自定义一个Author特性类。

正文


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
public class UserAttribute : Attribute
{
    public string Name { get; set; }
    public int Age { get; set; }
    public UserAttribute(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

[UserAttribute("刘备", 45)]
public class User
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void Show()
    {
        var attr = typeof(User).GetCustomAttributes(typeof(UserAttribute), true);
        var t = attr[0].GetType();
        var name = t.GetProperty("Name").GetValue(attr[0]).ToString();
        int age = int.Parse(t.GetProperty("Age").GetValue(attr[0]).ToString());
        this.Name = name;
        this.Age = age;
    }
}

image.png
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class LengthAttribute: Attribute
{
    /// <summary>
    /// 最小长度
    /// </summary>
    public int MinLength = 0;

    /// <summary>
    /// 最大长度
    /// </summary>
    public int MaxLength = 0;

    public LengthAttribute(int min, int max)
    {
        this.MinLength = min;
        this.MaxLength = max;
    }

    public bool Check(object obj)
    {
        int value=obj.ToString().Length;
        if (value > this.MinLength && value < this.MaxLength)
        {
            return true;
        }
        return false;
    }
}

public class User
{
    [LengthAttribute(5, 10)]
    public string Name { get; set; }
    public int Age { get; set; }
}

读取特性

public static class Manager
{
    public static void Show(User user)
        {
            if (Validate(user))
            {
                MessageBox.Show("OK");
            }
            else
            {
                MessageBox.Show("ERROR");
            }
        }

    public static bool Validate(this User obj)
    {
        Type type = typeof(User);
        PropertyInfo property = type.GetProperty("Name");
        //检查Name属性上面是否定义了CustomAttribute特性
        if (property.CustomAttributes.Count() > 0)
        {
            LengthAttribute attribute = (LengthAttribute)property.GetCustomAttribute(typeof(Attribute), true);
            if (attribute.Check(property.GetValue(obj)))
            {
                return true;
            }
        }
        return false;
    }
}

调用

private void btnShow_Click(object sender, EventArgs e)
{
    User user = new User();
    user.Name = "test001";
    user.Age = 100;
    Manager.Show(user);
}

image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容