发现C#的一个弱点
写了如下代码:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class TypeConditionAttribute<TValue> : Attribute
{
/// <summary>
/// The field name of type field
/// </summary>
public string TypeField { get; set; }
public TValue Value { get; set; }
public TypeConditionAttribute(string typeField, TValue value)
{
TypeField = typeField;
Value = value;
}
public bool Evaluate(object record)
{
FieldInfo fieldInfo = record.GetType().GetField(TypeField);
object value = fieldInfo.GetValue(record);
return this.Value.Equals((TValue)value);
}
}
public class TypeConditionAttribute<TValue> : Attribute
{
/// <summary>
/// The field name of type field
/// </summary>
public string TypeField { get; set; }
public TValue Value { get; set; }
public TypeConditionAttribute(string typeField, TValue value)
{
TypeField = typeField;
Value = value;
}
public bool Evaluate(object record)
{
FieldInfo fieldInfo = record.GetType().GetField(TypeField);
object value = fieldInfo.GetValue(record);
return this.Value.Equals((TValue)value);
}
}
结果不能编译,原因是“Attribute”是一个特性类,无法从它派生泛型类型。有点出乎意外。