C# 特性(Attribute)
系统梳理 C# 特性语法、三大预定义特性(AttributeUsage、Conditional、Obsolete)的真实默认值与编译行为,以及自定义特性四步开发流程,并附本地 csc.exe 实测与默认值勘误。
学完这一章,你能够
- 系统梳理 C# 特性语法、三大预定义特性(AttributeUsage、Conditional、Obsolete)的真实默认值与编译行为,以及自定义特性四步开发流程,并附本地 csc.exe 实测与默认值勘误。
特性定位与声明语法
特性(Attribute)是附加在程序集、类、结构、枚举、方法、属性或字段等目标元素之前的声明性方括号标签 `[...]`,用于在编译期向编译器传递指令,或在程序集元数据中嵌入可供运行时反射读取的附加描述信息。.NET 将特性分为预定义特性与自定义特性两类;书写语法为 `[AttributeName(positional_args, NamedProp = value, ...)]`,其中定位参数对应特性构造函数的必选形参,命名参数对应特性的公有可读写属性或字段(可选填写)。
三大预定义特性:AttributeUsage、Conditional 与 Obsolete
最常用的三项预定义特性为 `AttributeUsage`、`Conditional` 与 `Obsolete`。`AttributeUsage` 专门用于修饰自定义特性类本身,控制其合法应用范围:`validon` 接受 `AttributeTargets` 按位或组合(如 `AttributeTargets.Class | AttributeTargets.Method`,默认覆盖 `AttributeTargets.All`);`AllowMultiple` 决定同一目标元素上能否重复标注多个同类型特性(默认 `false`);`Inherited` 决定派生类及重写成员是否继承该特性。重要事实勘误:部分早期资料误称 `AttributeUsageAttribute.Inherited` 默认值为 `false`,本站本地 .NET Framework 4.x 实测 `new AttributeUsageAttribute(AttributeTargets.All)` 明确证实 `AllowMultiple` 默认为 `False` 而 `Inherited` 默认为 `True`。
`System.Diagnostics.ConditionalAttribute` 根据指定的预处理器符号(如 `[Conditional("DEBUG")]` 或 `[Conditional("TRACE")]`)决定是否编译对该方法的调用点。需注意三点:被标记方法本身仍会编译进程序集元数据,仅当调用方未定义对应符号时编译器才忽略调用语句;条件方法返回类型必须为 `void`;它常用于零开销的调试日志追踪。本站实测 `#define TRACE_DEMO` 下 `[Conditional("TRACE_DEMO")]` 调用全部记录,而 `[Conditional("UNDEF_TRACE_DEMO")]` 调用被编译器彻底跳过。
`System.ObsoleteAttribute` 用于将过时的类型或成员标记为废弃,并在迁移期向调用方提示替代方案。其构造函数接受说明字符串 `message` 与可选布尔值 `iserror`:当 `iserror` 省略或为 `false` 时,调用过时成员会产生编译器警告(CS0618);当 `iserror` 为 `true` 时,调用将直接触发编译器错误(CS0619)阻止构建。本站直接调用本地 `csc.exe` 编译调用 `[Obsolete(..., true)]` 方法的源码片段,实测确认编译失败并返回精确错误码 `CS0619`。
创建、构建与应用自定义特性
自定义特性用于将领域元数据(如缺陷审查记录、序列化规则或校验约束)直接随代码存入程序集元数据。完整流程包含四个步骤:声明继承自 `System.Attribute` 的特性类、通过构造函数与属性构建其数据结构、在目标程序元素上方用方括号应用特性,以及在运行时借助反射读取这些元数据(反射查询细节将在下一章展开)。
设计 `DeBugInfo` 自定义特性时,用 `[AttributeUsage(..., AllowMultiple = true)]` 允许同一类或方法附加多条缺陷记录,并让类派生自 `System.Attribute`(工程惯例通常以 `Attribute` 为后缀命名,使用时可省略后缀)。其构造函数接收三项必选定位参数:缺陷编号 `bugNo`、开发人员 `developer` 与审查日期 `lastReview`,以只读属性对外暴露;额外说明 `Message` 则定义为公有可读写属性作为可选命名参数(建议将其底层字段设为 `private` 避免公开字段与属性并存造成混淆)。
应用时将 `[DeBugInfo(...)]` 紧贴写在 `Rectangle` 类以及 `GetArea()`、`Display()` 等方法声明上方:由于启用了 `AllowMultiple = true`,`Rectangle` 类上可同时附加编号 `45` 与 `49` 两条特性,方法上既可传入可选的 `Message = ...` 也可省略(此时 `Message` 保持 `null`)。本站实测通过反射读出 `Rectangle` 类上 `45`/`49` 两条特性及方法上 `55`(含消息)与 `56`(消息为 `null`)两条特性,为下一章反射读取奠定基础。
运行 csc.exe (.NET Framework 4.x) AttributeUsage 默认值、Conditional、Obsolete CS0619 与 DeBugInfo 实测
#define TRACE_DEMO
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
namespace CSharpAttributeLab
{
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : Attribute
{
private readonly int bugNo;
private readonly string developer;
private readonly string lastReview;
private 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; }
}
}
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
internal class Rectangle
{
protected double length;
protected double width;
public Rectangle(double l, double w)
{
length = l;
width = w;
}
[DeBugInfo(55, "Zara Ali", "19/10/2012", Message = "Return type mismatch")]
public double GetArea()
{
return length * width;
}
[DeBugInfo(56, "Zara Ali", "19/10/2012")]
public string FormatSummary()
{
return string.Format("{0}x{1}={2}", length, width, GetArea());
}
}
internal class ConditionalHost
{
public static List<string> TraceLog = new List<string>();
[Conditional("TRACE_DEMO")]
public static void LogActive(string msg)
{
TraceLog.Add(msg);
}
[Conditional("UNDEF_TRACE_DEMO")]
public static void LogSkipped(string msg)
{
TraceLog.Add(msg);
}
}
internal class LegacyService
{
[Obsolete("Use NewMethod instead", false)]
public static string WarnOldMethod()
{
return "old";
}
[Obsolete("Don't use OldMethod, use NewMethod instead", true)]
public static string ErrorOldMethod()
{
return "err";
}
}
internal class Program
{
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
// Case 1: AttributeUsageAttribute defaults and target flags
AttributeUsageAttribute defUsage = new AttributeUsageAttribute(AttributeTargets.All);
object[] usageAttrs = typeof(DeBugInfo).GetCustomAttributes(typeof(AttributeUsageAttribute), false);
AttributeUsageAttribute dbgUsage = (AttributeUsageAttribute)usageAttrs[0];
bool hasClassAndMethod = (dbgUsage.ValidOn & AttributeTargets.Class) != 0
&& (dbgUsage.ValidOn & AttributeTargets.Method) != 0
&& (dbgUsage.ValidOn & AttributeTargets.Interface) == 0;
string actual1 = string.Format(
"defAllow={0};defInh={1};dbgAllow={2};dbgInh={3};targetsOk={4}",
defUsage.AllowMultiple, defUsage.Inherited, dbgUsage.AllowMultiple, dbgUsage.Inherited, hasClassAndMethod
);
cases.Add(CaseJson(
"attribute_usage_defaults_and_targets",
"Verify AttributeUsageAttribute real defaults (AllowMultiple=False, Inherited=True) and custom ValidOn flags",
"defAllow=False;defInh=True;dbgAllow=True;dbgInh=True;targetsOk=True",
actual1
));
// Case 2: Conditional attribute active vs omitted calls
ConditionalHost.TraceLog.Clear();
ConditionalHost.LogActive("Main");
ConditionalHost.LogSkipped("ShouldNotAppear");
ConditionalHost.LogActive("Func1");
ConditionalHost.LogActive("Func2");
string actual2 = string.Join("->", ConditionalHost.TraceLog.ToArray());
cases.Add(CaseJson(
"conditional_attribute_compilation",
"Verify [Conditional(\"TRACE_DEMO\")] executes when symbol defined while [Conditional(\"UNDEF_TRACE_DEMO\")] call is omitted",
"Main->Func1->Func2",
actual2
));
// Case 3: Obsolete metadata + real csc.exe CS0619 compile error test
ObsoleteAttribute warnAttr = (ObsoleteAttribute)typeof(LegacyService)
.GetMethod("WarnOldMethod")
.GetCustomAttributes(typeof(ObsoleteAttribute), false)[0];
ObsoleteAttribute errAttr = (ObsoleteAttribute)typeof(LegacyService)
.GetMethod("ErrorOldMethod")
.GetCustomAttributes(typeof(ObsoleteAttribute), false)[0];
string tempDir = Path.Combine(Path.GetTempPath(), "csharplab-obs-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
bool cscBlockedWith619 = false;
try
{
string srcPath = Path.Combine(tempDir, "ObsTest.cs");
string exePath = Path.Combine(tempDir, "ObsTest.exe");
File.WriteAllText(srcPath,
"using System;\n" +
"class P {\n" +
" [Obsolete(\"Don't use OldMethod, use NewMethod instead\", true)]\n" +
" static void OldMethod() {}\n" +
" static void Main() { OldMethod(); }\n" +
"}\n",
Encoding.UTF8);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = @"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe";
psi.Arguments = string.Format("/nologo /utf8output /out:\"{0}\" \"{1}\"", exePath, srcPath);
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.CreateNoWindow = true;
using (Process p = Process.Start(psi))
{
string outTxt = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd();
p.WaitForExit(30000);
cscBlockedWith619 = (p.ExitCode != 0 && outTxt.IndexOf("CS0619", StringComparison.Ordinal) >= 0);
}
}
finally
{
if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true);
}
string actual3 = string.Format("warnErr={0};errErr={1};csc619={2}", warnAttr.IsError, errAttr.IsError, cscBlockedWith619);
cases.Add(CaseJson(
"obsolete_attribute_warning_and_error",
"Verify ObsoleteAttribute IsError metadata and confirm csc.exe rejects iserror=true call with CS0619",
"warnErr=False;errErr=True;csc619=True",
actual3
));
// Case 4: Custom DeBugInfo attribute application on class & methods
object[] clsAttrs = typeof(Rectangle).GetCustomAttributes(typeof(DeBugInfo), false);
List<int> clsBugs = new List<int>();
foreach (object a in clsAttrs)
{
clsBugs.Add(((DeBugInfo)a).BugNo);
}
clsBugs.Sort();
DeBugInfo areaAttr = (DeBugInfo)typeof(Rectangle).GetMethod("GetArea").GetCustomAttributes(typeof(DeBugInfo), false)[0];
DeBugInfo dispAttr = (DeBugInfo)typeof(Rectangle).GetMethod("FormatSummary").GetCustomAttributes(typeof(DeBugInfo), false)[0];
string actual4 = string.Format(
"cls={0},{1};area={2}:{3};disp={4}:{5}",
clsBugs[0], clsBugs[1], areaAttr.BugNo, areaAttr.Message, dispAttr.BugNo, dispAttr.Message == null ? "null" : dispAttr.Message
);
cases.Add(CaseJson(
"custom_debuginfo_attribute_application",
"Verify multiple DeBugInfo custom attributes applied to Rectangle class and its methods with positional and named args",
"cls=45,49;area=55:Return type mismatch;disp=56:null",
actual4
));
Console.WriteLine(string.Format(
"{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
Environment.Version.ToString(),
string.Join(",", cases.ToArray())
));
}
}
}
- 核对 AttributeUsage 默认 AllowMultiple=False/Inherited=True、Conditional 符号命中与跳过、Obsolete iserror=true 触发 CS0619 编译错误及 DeBugInfo 多重应用全部通过。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
当前源码 SHA256:30a5a78213f7f3274b22856388bd123e02975621371135abc29cd7eba3e02712
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
ZIP SHA256:860405799d24d44119beb5a3e5bbbce858127003b45f87c4248c2b000668d2ce
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`[Conditional("DEBUG")]` 在未定义 `DEBUG` 符号时,是阻止目标方法被编译,还是省略调用处的方法调用?`AttributeUsageAttribute.Inherited` 的真实默认值是什么?
展开参考解答
`[Conditional]` 不会阻止目标方法体被编译进程序集,而是让编译器在调用方未定义该符号时省略所有对该方法的调用(且方法返回类型必须为 `void`)。`AttributeUsageAttribute.Inherited` 的真实默认值为 `true`(而 `AllowMultiple` 默认值为 `false`)。