98.C# 自定义特性

98.C# 自定义特性摘要可通过定义特性类创建自己的自定义特性,特性类是直接或间接派生自 Attribute 的类,可快速轻松地识别元数据中的特性定义。假设我们希望使

大家好,欢迎来到IT知识分享网。

摘要


可通过定义特性类创建自己的自定义特性,特性类是直接或间接派生自 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; } }
98.C# 自定义特性

[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); }
98.C# 自定义特性

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/54217.html

(0)
上一篇 2024-07-30 20:33
下一篇 2024-08-09 16:15

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信