换句话说,如果每个类都没有(“必须有”)自定义属性(例如Author和Version ),那么有可能创建甚至不编译(假设检查代码没有删除)的程序集吗?
以下是我在运行时用于查询的代码:
using System;
using System.Reflection;
using System.Collections.Generic;
namespace ForceMetaAttributes
{
[System.AttributeUsage ( System.AttributeTargets.Method, AllowMultiple = true )]
class TodoAttribute : System.Attribute
{
public TodoAttribute ( string message )
{
Message = message;
}
public readonly string Message;
}
[System.AttributeUsage ( System.AttributeTargets.Class |
System.AttributeTargets.Struct, AllowMultiple = true )]
public class AttributeClass : System.Attribute
{
public string Description { get; set; }
public string MusHaveVersion { get; set; }
public AttributeClass ( string description, string mustHaveVersion )
{
Description = description;
MusHaveVersion = mustHaveVersion ;
}
} //eof class
[AttributeClass("AuthorName" , "1.0.0")]
class ClassToDescribe
{
[Todo ( " A todo message " )]
static void Method ()
{ }
} //eof class
//how to get this one to fail on compile
class AnotherClassToDescribe
{
} //eof class
class QueryApp
{
public static void Main()
{
Type type = typeof(ClassToDescribe);
AttributeClass objAttributeClass;
//Querying Class Attributes
foreach (Attribute attr in type.GetCustomAttributes(true))
{
objAttributeClass = attr as AttributeClass;
if (null != objAttributeClass)
{
Console.WriteLine("Description of AnyClass:\n{0}",
objAttributeClass.Description);
}
}
//Querying Class-Method Attributes
foreach(MethodInfo method in type.GetMethods())
{
foreach (Attribute attr in method.GetCustomAttributes(true))
{
objAttributeClass = attr as AttributeClass;
if (null != objAttributeClass)
{
Console.WriteLine("Description of {0}:\n{1}",
method.Name,
objAttributeClass.Description);
}
}
}
//Querying Class-Field (only public) Attributes
foreach(FieldInfo field in type.GetFields())
{
foreach (Attribute attr in field.GetCustomAttributes(true))
{
objAttributeClass= attr as AttributeClass;
if (null != objAttributeClass)
{
Console.WriteLine("Description of {0}:\n{1}",
field.Name,objAttributeClass.Description);
}
}
}
Console.WriteLine ( "hit Enter to exit " );
Console.ReadLine ();
} //eof Main
} //eof class
} //eof namespace
//uncomment to check whether it works with external namespace
//namespace TestNamespace {
// class Class1 { }
// class Class2 { }
//}
编辑:只是为了证明我的答案是正确的。我认为casperOne提供了问题的正确答案。
然而,问这个问题的原因似乎是weak。也许我应该开始使用一些外部工具,比如:FinalBuilder或创建单元测试来检查这个“需求”,使用Pex、Nunit或其他单元测试框架……
EDIT我在答案的末尾添加了一个控制台程序的小code snippet,用于执行检查...请随时评论、批评或提出改进建议
我再一次意识到这个“需求”应该在“签入”之前作为单元测试的一部分来实现。
https://stackoverflow.com/questions/753255
复制相似问题