
属性用于向程序添加元数据,例如编译器指令和其他信息,例如注释、描述、方法和类。
.Net Framework 允许创建可用于存储声明性信息并可在运行时检索的自定义属性。
新的自定义属性派生自 System.Attribute 类。
//a custom attribute BugFix to be assigned to a class and its members [AttributeUsage( AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class DeBugInfo : System.Attribute
让我们构造一个名为 DeBugInfo 的自定义属性,它存储通过调试任何程序获得的信息。
DeBugInfo 类具有三个私有属性,用于存储前三个信息,还有一个公共属性,用于存储消息。因此,错误编号、开发人员姓名和审核日期是 DeBugInfo 类的位置参数,消息是可选或命名参数。
让我们看看如何 -
//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : System.Attribute {
private int bugNo;
private string developer;
private string lastReview;
public string message;
public DeBugInfo(int bg, string dev, string d) {
this.bugNo = bg;
this.developer = dev;
this.lastReview = d;
}
public int BugNo {
get {
return bugNo;
}
}
public string Developer {
get {
return developer;
}
}
public string LastReview {
get {
return lastReview;
}
}
public string Message {
get {
return message;
}
set {
message = value;
}
}
}以上就是如何在C#中构造自定义属性?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号