反射,从伙伴类中获取DataAnnotation属性

时间:2010-04-09 22:09:22

标签: .net reflection attributes

我需要检查属性是否在其伙伴类中定义了特定属性:

[MetadataType(typeof(Metadata))]
public sealed partial class Address
{
    private sealed class Metadata
    {
        [Required]
        public string Address1 { get; set; }

        [Required]
        public string Zip { get; set; }
    }
}

如何检查哪些属性已定义Required属性?

谢谢。

3 个答案:

答案 0 :(得分:8)

可以使用嵌套类型的探索来完成:

public IEnumerable<PropertyInfo> GetRequiredProperties()
{
    var nestedTypes = typeof(Address).GetNestedTypes(BindingFlags.NonPublic);

    var nestedType = nestedTypes.First(); // It can be done for all types

    var requiredProperties =
        nestedType.GetProperties()
            .Where(property => 
                           property.IsDefined(typeof(RequiredAttribute), false));

    return requiredProperties;
}

用法示例:

[Test]
public void Example()
{
    var requiredProperties = GetRequiredProperties();
    var propertiesNames = requiredProperties.Select(property => property.Name);

    Assert.That(propertiesNames, Is.EquivalentTo(new[] { "Address1", "Zip" }));
}

答案 1 :(得分:0)

虽然不如Elisha的解决方案那么优雅,但它也有效:)

您的属性:

[AttributeUsage(AttributeTargets.All, AllowMultiple=false)]
class RequiredAttribute : System.Attribute
{
    public string Name {get; set; }

    public RequiredAttribute(string name)
    {
        this.Name = name;
    }

    public RequiredAttribute()
    {
        this.Name = "";
    }
}

某些课程:

class Class1
{
    [Required]
    public string Address1 { get; set; }

    public string Address2 { get; set; }

    [Required]
    public string Address3 { get; set; }
}

用法:

Class1 c = new Class1();
RequiredAttribute ra = new RequiredAttribute();

Type class1Type = c.GetType();
PropertyInfo[] propInfoList = class1Type.GetProperties();
foreach (PropertyInfo p in propInfoList)
{
    object[] a = p.GetCustomAttributes(true);
    foreach (object o in a)
    {
        if (o.GetType().Equals(ra.GetType()))
        {
            richTextBox1.AppendText(p.Name + " ");
        }
    }
}

答案 2 :(得分:0)

以下是我的解决方案usinjg AssociatedMetadataTypeTypeDescriptionProvider

var entity = CreateAddress();
var type = entity.GetType();
var metadata = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();
var properties = new AssociatedMetadataTypeTypeDescriptionProvider(type, metadata.MetadataClassType).GetTypeDescriptor(type).GetProperties();
bool hasAttribute = HasMetadataPropertyAttribute(properties, "Name", typeof(RequiredAttribute));

private static bool HasMetadataPropertyAttribute(PropertyDescriptorCollection properties, string name, Type attributeType)
{
    var property = properties[name];
    if ( property == null )
        return false;

    var hasAttribute = proeprty.Attributes.Cast<object>().Any(a => a.GetType() == attributeType);
    return hasAttribute;
}