How is this useful? It's useful to me in that it makes it very easy to add new attributes, and the code is cleanly separated so there is less chance of breaking things. It's useful to everyone else in that you can now add your own custom attributes OR make use of existing attributes that may already be decorating your code.
Here's a good example. Just about every serialization framework out there has some way of excluding properties from being serialized. Me too. Mine is called JsonExIgnore. You may be switching from an existing framework, or using 2 frameworks simultaneously. The built-in XmlSerializer uses the XmlIgnore attribute. I've added an AttributeProcessor class for it which is not turned on by default, but is very easy to add in.
Serializer serializer = new Serializer(typeof(MyClass));
// let's just use the XmlIgnore attribute that we already
// decorated our classes with so we don't have to type anymore
serializer.TypeHandlerFactory.AttributeProcessors.Add(new XmlIgnoreAttributeProcessor());
Here is the code for the XmlIgnoreAttributeProcessor:
public class XmlIgnoreAttributeProcessor : AttributeProcessor
{
public override void Process(MetaDataBase metaData, ICustomAttributeProvider attributeProvider, SerializationContext serializationContext)
{
if (metaData is IPropertyData)
{
IPropertyData property = (IPropertyData)metaData;
if (attributeProvider.IsDefined(typeof(XmlIgnoreAttribute), false))
property.Ignored = true;
}
}
}
TypeData, PropertyData, FieldData all extend from MetaDataBase. They represent Types, properties, and fields respectively. If you're only interested in one type of metadata then you need to check the metaData property to see what it is. IPropertyData is an interface that both PropertyData and FieldData implement. ICustomAttributeProvider is a .NET class that Reflection classes such as Type, MemberInfo, etc implement so that you can read their attributes. You query for the attribute(s) that your processor knows how to handle and then react accordingly if you find any. And that's it.
0 comments:
Post a Comment