我想得到我的类的哪些属性具有带有具体字符串的确切属性。我有这个实现(属性和类):
[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
的属性。
我该怎么做?
答案 0 :(得分:7)
var props = theType
.GetProperties()
.Where(
prop => ((IsDbMandatory[])prop
.GetCustomAttributes(typeof(IsDbMandatory), false))
.Any(att => att.tableField == "blabla")
);