如何解决C#,过滤自定义属性属性值
考虑一个课程:
public class Dog
{
[Key]
[TableField(Name= "Jersey",Inoculated = false)]
public string Param1{ get; set; }
[TableField(Name= "Daisy",Inoculated = true)]
public string Param2{ get; set; }
[TableField(Name= "Jeremy",Inoculated = true)]
public string Param3{ get; set; }
}
还有一个属性类:
public sealed class TableField : Attribute
{
public string Name { get; set; }
public bool Inoculated { get; set; }
}
这与实际示例有点不同,但是我需要从typeof(Dog)(默认类值)中选择所有TableField.Name属性值,其中TableField.Inoculated == true。
最好的尝试,不知道从这里去哪里
var names = typeof(Dog).GetProperties()
.Where(r => r.GetCustomAttributes(typeof(TableField),false).Cast<TableField>()
.Any(x => x.Inoculated));
解决方法
如果您需要通过属性从属性中进行选择,则以下示例可能对您有用。
var dogType = typeof(Dog);
var names = dogType.GetProperties()
.Where(x => Attribute.IsDefined(x,typeof(TableField)))
.Select(x => x.GetCustomAttribute<TableField>())
.Where(x => x.Inoculated == true)
.Select(x=>x.Name);
,
通过使用System.Reflection,您可以执行以下操作:
public static Dictionary<string,string> GetDogNames()
{
var namesDict = new Dictionary<string,string>();
var props = typeof(Dog).GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
if (attr is TableField tableField && tableField.Inoculated)
{
string propName = prop.Name;
string auth = tableField.Name;
namesDict.Add(propName,auth);
}
}
}
return namesDict;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。