using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace CSharpReflectionLab
{
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : Attribute
{
public readonly string Url;
private string topic;
public string Topic
{
get { return topic; }
set { topic = value; }
}
public HelpAttribute(string url)
{
this.Url = url;
}
}
[Help("Information on the class MyClass", Topic = "ReflectionBasics")]
internal class AnnotatedTarget
{
}
[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
{
public double Length { get; set; }
public double Width { get; set; }
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 Describe()
{
return string.Format(CultureInfo.InvariantCulture, "{0}x{1}={2}", Length, Width, GetArea());
}
}
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: MemberInfo + HelpAttribute reflection
MemberInfo info = typeof(AnnotatedTarget);
object[] helpAttrs = info.GetCustomAttributes(true);
HelpAttribute h = helpAttrs[0] as HelpAttribute;
string actual1 = string.Format("type={0};url={1};topic={2}", h.GetType().Name, h.Url, h.Topic);
cases.Add(CaseJson(
"memberinfo_help_attribute_inspection",
"Inspect HelpAttribute attached to AnnotatedTarget via MemberInfo.GetCustomAttributes(true)",
"type=HelpAttribute;url=Information on the class MyClass;topic=ReflectionBasics",
actual1
));
// Case 2: Inspect Rectangle class & method DeBugInfo metadata
Type rectType = typeof(Rectangle);
List<string> classRecords = new List<string>();
foreach (object attr in rectType.GetCustomAttributes(typeof(DeBugInfo), false))
{
DeBugInfo dbi = attr as DeBugInfo;
if (dbi != null)
{
classRecords.Add(string.Format("{0}:{1}:{2}", dbi.BugNo, dbi.Developer, dbi.Message ?? ""));
}
}
classRecords.Sort(StringComparer.Ordinal);
List<string> methodRecords = new List<string>();
foreach (MethodInfo m in rectType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
foreach (object attr in m.GetCustomAttributes(typeof(DeBugInfo), true))
{
DeBugInfo dbi = attr as DeBugInfo;
if (dbi != null)
{
methodRecords.Add(string.Format("{0}#{1}:{2}", m.Name, dbi.BugNo, dbi.Message ?? ""));
}
}
}
methodRecords.Sort(StringComparer.Ordinal);
string actual2 = string.Join("|", classRecords.ToArray()) + "||" + string.Join("|", methodRecords.ToArray());
cases.Add(CaseJson(
"debuginfo_class_and_method_metadata",
"Inspect class-level and method-level DeBugInfo custom attributes on Rectangle via Type and MethodInfo",
"45:Zara Ali:Return type mismatch|49:Nuha Ali:Unused variable||Describe#56:|GetArea#55:Return type mismatch",
actual2
));
// Case 3: Dynamic instantiation, late-bound method invocation & property access
object dynRect = Activator.CreateInstance(rectType, new object[] { 4.5, 7.5 });
MethodInfo areaMethod = rectType.GetMethod("GetArea");
double area1 = (double)areaMethod.Invoke(dynRect, null);
PropertyInfo widthProp = rectType.GetProperty("Width");
widthProp.SetValue(dynRect, 10.0, null);
double area2 = (double)areaMethod.Invoke(dynRect, null);
string actual3 = string.Format(CultureInfo.InvariantCulture, "area1={0};area2={1}", area1, area2);
cases.Add(CaseJson(
"dynamic_instantiation_and_late_binding",
"Verify Activator.CreateInstance, MethodInfo.Invoke, and PropertyInfo.SetValue late binding",
"area1=33.75;area2=45",
actual3
));
// Case 4: Assembly -> Module -> Type -> MemberInfo hierarchy
Assembly asm = rectType.Assembly;
Module mod = rectType.Module;
bool sameType = mod.GetType("CSharpReflectionLab.Rectangle") == rectType;
bool safeFilter = rectType.GetCustomAttributes(typeof(HelpAttribute), false).Length == 0;
string actual4 = string.Format("hasAsm={0};sameType={1};safeFilter={2}", asm != null, sameType, safeFilter);
cases.Add(CaseJson(
"assembly_module_type_hierarchy",
"Verify Assembly -> Module -> Type lookup and typed GetCustomAttributes filtering safety",
"hasAsm=True;sameType=True;safeFilter=True",
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-reflection-lab/ExploreReflection.cs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreReflection.cs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a1321.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1352.zip