使用C# 4.0,获取具有指定属性和属性数据的类属性。

4

我想知道我的类有哪些属性具有一个具体字符串的确切属性。以下是我的实现(属性和类):

[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个回答

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

props 是什么类型?是 PropertyInfo[] 还是只有 PropertyInfo(没有数组)?我想要将 props 强类型化,以便更清晰、更容易地访问其属性。 - ferpega
@FerPt,它是IEnumerable<PropertyInfo>。你可以在末尾添加.ToArray()来得到一个PropertyInfo[] - Darin Dimitrov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接