日期:2014-05-20 浏览次数:20933 次
[AttributeUsage(AttributeTargets.Class), AllowMultiple=true]
sealed class DecoratorAttribute : Attribute
{
public readonly object Injector;
private Type type;
public DecoratorAttribute(Type type)
{
if (type == null) throw new ArgumentNullException("type");
this.type = type;
Injector = (new Assembler()).Create(this.type);
}
public Type Type { get { return this.type; } }
}
static class AttributeHelper
{
public static T Injector(object target)//[color=#FF0000]这个泛型怎么解释我不太懂[/color]
where T : class
{
if (target == null) throw new ArgumentNullException("target");
Type targetType = target.GetType();
object[] attributes = targetType.GetCustomAttributes(
typeof(DecoratorAttribute), false);
if ((attributes == null) || (attributes.Length <= 0)) return null;
foreach (DecoratorAttribute attribute in
(DecoratorAttribute [])attributes)
if (attribute.Type == typeof(T))// if (attribute.Type.GetInterfaces().Contains(typeof(T)))
return (T)attribute.Injector;
return null;
}
}
[Decorator(typeof(ITimeProvider)]//[color=#FF0000]这里应该使用可实例化的类吧,不应该使用接口吧[/color]
class Client
{
public int GetYear()
{
ITimeProvider provider =
AttributeHelper.Injector(this);
return provider.CurrentDate.Year;
}
}