c#4.0使用(指定的属性和attribute.data)获取类属性

时间:2011-04-07 09:51:14

标签: c# reflection c#-4.0 custom-attributes

我想得到我的类的哪些属性具有带有具体字符串的确切属性。我有这个实现(属性和类):

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class IsDbMandatory : System.Attribute
{
    public readonly string tableField;

    public IsDbMandatory (string tableField)
    {
        this.tableField= TableField;
    }
}

public Class MyClass 
{
    [IsDbMandatory("ID")]
    public int MyID { get; set; }
}

然后我以这种方式获得具有具体属性的属性:

public class MyService
{
   public bool MyMethod(Type theType, string myAttributeValue)
   {            
       PropertyInfo props = 
           theType.GetProperties().
                  Where(prop => Attribute.IsDefined(prop, typeof(IsDbMandatory))); 
   }
}

但我只需要具有具体属性isDbMandatory和具体字符串myAttributeValue的属性。

我该怎么做?

1 个答案:

答案 0 :(得分:7)

var props = theType
    .GetProperties()
    .Where(
        prop => ((IsDbMandatory[])prop
            .GetCustomAttributes(typeof(IsDbMandatory), false))
            .Any(att => att.tableField == "blabla")
    );