“复制”属性的概念已经过时了。但是,您可以在代码中做一些有意义的事情来检查是否应用了该属性。您可以使用另一个属性告诉代码它应该使用另一种类型来验证 [Required] 属性。例如:
[AttributeUsage(AttributeTargets.Class)]
public class AttributeProviderAttribute : Attribute {
public AttributeProviderAttribute(Type t) { Type = t; }
public Type Type { get; set; }
}
你会像这样使用它:
public class Foo {
[Required]
public string Name { get; set; }
}
[AttributeProvider(typeof(Foo))]
public class Bar {
public string Name { get; set; }
}
检查属性的代码可能如下所示:
static bool IsRequiredProperty(Type t, string name) {
PropertyInfo pi = t.GetProperty(name);
if (pi == null) throw new ArgumentException();
// First check if present on property as-is
if (pi.GetCustomAttributes(typeof(RequiredAttribute), false).Length > 0) return true;
// Then check if it is "inherited" from another type
var prov = t.GetCustomAttributes(typeof(AttributeProviderAttribute), false);
if (prov.Length > 0) {
t = (prov[0] as AttributeProviderAttribute).Type;
return IsRequiredProperty(t, name);
}
return false;
}
请注意此代码如何允许链接属性提供程序。