[英]Custom attributes in C#
我的页面有一个自定义属性,如下所示:
[PageDefinition("My page", "~/Parts/MyPage.aspx")]
我的PageDefinition如下所示,其中为Title,Url,IsPage和IsUserControl设置了AttributeItemDefinitions
public class PageDefinition : AttributeItemDefinitions
{
public PageDefinition(string title, string url)
: this()
{
Title = title;
Url = Url;
}
public PageDefinition()
{
IsPage = true;
IsUserControl = false;
}
}
但是我找不到任何将具有该属性的所有页面添加到占位符的好方法,在该占位符中所有链接都应列出标题和URL。 你有什么好主意吗? 谢谢你的帮助。
当我创建了在类上定义一些元数据的自定义属性时,我通常会构建一个小的例程,该例程使用反射来扫描程序集的所有类。
在我当前的项目中,我使用的是IoC框架(其他故事),而不是在自定义配置文件中对其进行配置,我为自己构建了一个ComponentAttribute,它定义了一个类所属的接口。 (从鸟瞰的角度来看:我稍后向IoC框架询问接口,它知道如何实例化实现该接口的类以及它们如何组合在一起)
要配置该IoC框架,我需要调用某个类的成员,并告诉它接口映射存在的类。
ioc.ConfigureMapping(classType, interfaceType)
为了找到所有这些映射,我在一个助手类中使用了以下两种方法
internal static void Configure(IoCContainer ioc, Assembly assembly)
{
foreach (var type in assembly.GetTypes())
AddToIoCIfHasComponentAttribute(type, ioc);
}
internal static void AddToIoCIfHasComponentAttribute(Type type, IoC ioc)
{
foreach (ComponentAttribute att in type.GetCustomAttributes(typeof(ComponentAttribute), false))
{
ioc.ConfigureMapping(attribute.InterfaceType, type);
}
}
我在这里所做的是在第一种方法中枚举所有程序集的类型,而不是在第二种方法中评估属性。
回到您的问题:
使用类似的方法,您可以找到所有标记的类,并将它们与您在属性中定义的所有数据(页面路径等)一起记录在容器(ArrayList或类似的容器)中。
在Visual Studio中构建程序时,通常会有一个或多个项目。 对于每个项目,您将获得一个不同的程序集(.dll或.exe文件)。 上面的代码将检查一个程序集中的所有类。 这样看来,程序集就是收集的.cs文件的集合。 因此,您要搜索程序集,而不是.cs文件的目录(它们是源代码,而不是正在运行的应用程序的一部分)。
因此,可能缺少的是:当您要搜索类时,如何从代码中访问程序集? 您只需获取您知道的任何类(即您的其他类所在的程序集/项目中)并通过调用获取其所在的程序集
var assembly = typeof(MyDummyClass).Assembly;
然后,您将调用从上面的代码派生的内容
AnalyzeClasses(assembly)
和AnalyzeClasses看起来像
internal static void AnalyzeClasses(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
AnalzyeSingleClass(type);
}
internal static void AnalzyeSingleClass(Type type)
{
foreach (MyCustomAttribute att in type.GetCustomAttributes(typeof(MyCustomAttribute), false))
{
Console.WriteLine("Found MyCustomAttribute with property {0} on class {1}",
att.MyCustomAttributeProperty,
type);
}
}
而且,您只需在运行应用程序代码之前调用所有这些功能,例如,在main()顶部(对于应用程序),或者如果高级操作很困难,也可以在需要收集数据时按需调用此函数。 (例如,从ASP.NET页)
可能超出您的需要,但...
我在项目中一直都遇到这种模式,因此我实现了一个类型加载器,该类型加载器可以与用户定义的委托一起提供,用于类型搜索匹配。
http://www.codeproject.com/KB/architecture/RuntimeTypeLoader.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.