在线代码实验室
运行 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())
));
}
}
}
本例需在 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
入口文件:projects/csharp-attribute-lab/ExploreAttribute.cs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreAttribute.cs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a1321.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1320.zip