从代码中读取属性
读取属性并检查其中的数据比使用属性或创建属性显著地更加复杂。读取属性要求开发人员要对如何使用一个对象的反射信息有个基本了解。如果你不熟悉反射机制,可以阅读“应用反射”系列文章。
假设我们正在查看一个类,我们想知道该类的那个properties使用了Alias属性以及都有哪些别名。列表E实现了这个功能。
列表 E
Private Dictionary<string, string> GetAliasListing(Type destinationType)
{
//Get all the properties that are in the
// destination type.
PropertyInfo[] destinationProperties = destinationType.GetProperties();
Dictionary<string, string> aliases = newDictionary<string, string>();
for each (PropertyInfo property in destinationProperties)
{
//Get the alias attributes.
object[] aliasAttributes =
property. GetCustomAttributes( typeof(Alias), true);
//Loop through the alias attributes and
// add them to the dictionary.
foreach (object attribute in aliasAttributes)
foreach (string name in ((Alias)attribute).Names)
aliases.Add(name, property.Name);
//We also need to add the property name
// as an alias.
aliases.Add(property.Name, property.Name);
}
return aliases;
}
这段代码最重要的地方是对GetCustomAttributes的调用以及循环遍历属性提取别名的地方。
GetCustomAttributes方法可以在我们从对象类型中提取的PropertyInfo类中找到。在上面的应用中,我们将要查询的属性类型作为参数传给GetCustomAttributes方法,同时还将“true”传递给该方法使得可以列出继承的属性。如何发现匹配的属性,GetCustomAttributes方法将返回一个对象数组。还有另外一种超负荷方法可以列出property上的所有属性,而不管属性类型是什么。
一旦有了属性,我们需要检查它们并从中提取需要的信息。这可以通过遍历由GetCustomAttributes方法得到的对象数组并将每个对象映射成我们要查询的属性来完成。在完成映射后,我们就可以像访问任意其它类的properties一样来访问属性的properties。
正如我在前面所说,读取属性是最困难的部分。然而,一旦我们写后读取属性的代码后,将来回忆和实施起来就相当容易了。
应用示例
我强烈建议你下载本文包含的这个应用示例。这个应用示例在一个简单的Windows应用中实现了下面的属性,并演示了如何读取和使用它们。
示例应用中包含了实现和读取属性每一步的注释,仔细看一下,我敢保证你会发现一些在自己的应用中可以利用的功能。

