C# 中的属性与序列化:深入解析与应用
1. System.AttributeUsageAttribute 限制属性装饰范围
大多数属性仅用于装饰特定的构造。例如,使用CommandLineOptionAttribute装饰类或程序集是没有意义的。为避免属性的不当使用,可使用System.AttributeUsageAttribute装饰自定义属性,以下是示例代码:
[AttributeUsage(AttributeTargets.Property)] public class CommandLineSwitchAliasAttribute : Attribute { // ... }若属性使用不当,如下面的代码,会导致编译时错误:
// ERROR: The attribute usage is restricted to properties [CommandLineSwitchAlias("?")] class CommandLineInfo { }AttributeUsageAttribute的构造函数接受一个AttributesTargets标志,该枚举列出了运行时允许属性装饰的所有可能目标。例如,若允许CommandLineSwitchAliasAttribute用于字段,可按如下方式