C#,过滤自定义属性 属性 值
C#, filter custom attribute property values
考虑 class:
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; }
}
还有一个属性class:
public sealed class TableField : Attribute
{
public string Name { get; set; }
public bool Inoculated { get; set; }
}
这与现实生活中的例子有点远,但我需要的是 select 来自 typeof(Dog) 的所有 TableField.Name 属性 值(默认 class值)其中 TableField.Inoculated == true.
最好的尝试,不知道从哪里开始:
var names = typeof(Dog).GetProperties()
.Where(r => r.GetCustomAttributes(typeof(TableField), false).Cast<TableField>()
.Any(x => x.Inoculated));
如果您需要 select 按属性从属性中获取,以下示例可能对您有用。
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;
}
考虑 class:
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; }
}
还有一个属性class:
public sealed class TableField : Attribute
{
public string Name { get; set; }
public bool Inoculated { get; set; }
}
这与现实生活中的例子有点远,但我需要的是 select 来自 typeof(Dog) 的所有 TableField.Name 属性 值(默认 class值)其中 TableField.Inoculated == true.
最好的尝试,不知道从哪里开始:
var names = typeof(Dog).GetProperties()
.Where(r => r.GetCustomAttributes(typeof(TableField), false).Cast<TableField>()
.Any(x => x.Inoculated));
如果您需要 select 按属性从属性中获取,以下示例可能对您有用。
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;
}