我有一个属性,它本身就有属性。我想访问这些属性之一(布尔值)并检查它是否正确。我能够检查属性是否已设置,但这就是全部..至少对于 linq 来说是这样。
属性:
public class ImportParameter : System.Attribute
{
private Boolean required;
public ImportParameter(Boolean required)
{
this.required = required;
}
}
Example:
[ImportParameter(false)]
public long AufgabeOID { get; set; }
到目前为止我所拥有的:
var properties = type.GetProperties()
.Where(p => Attribute.IsDefined(p, typeof(ImportParameter)))
.Select(p => p.Name).ToList();
我玩了一下,但我似乎无法验证所需的属性是否已设置。
首先,如果你想访问必填字段,你需要将其公开,最好是公共财产:
public class ImportParameter : System.Attribute
{
public Boolean Required {get; private set;}
public ImportParameter(Boolean required)
{
this.Required = required;
}
}
那么您可以使用此查询 Linq 来搜索“Required”属性设置为 false 的属性:
var properties = type.GetProperties()
.Where(p => p.GetCustomAttributes() //get all attributes of this property
.OfType<ImportParameter>() // of type ImportParameter
.Any(a=>a.Required == false)) //that have the Required property set to false
.Select(p => p.Name).ToList();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)