C# - 获取Linq属性属性
问题描述:
我有一个属性本身具有属性。我想访问其中的一个属性(一个布尔值)并检查它是否为真。我能够检查属性是否设置,但是关于所有......至少在linq中。C# - 获取Linq属性属性
属性:
public class ImportParameter : System.Attribute
{
private Boolean required;
public ImportParameter(Boolean required)
{
this.required = required;
}
}
例子:
[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搜索必需属性设置为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();
答
你必须作出必要的财产公开,像
public class ImportParameter : System.Attribute
{
public Boolean Required {get; private set;}
public ImportParameter(Boolean required)
{
this.Required = required;
}
}
现在,你应该能够访问您的属性对象。
请注意,通过使用public <DataType> <Name> {get; private set;}
您的财产是公开的,但只能设置为私人。
经过一个完整的工作示例:
using System;
using System.Linq;
public class Program
{
[ImportParameter(false)]
public Foo fc {get;set;}
public static void Main()
{
var required = typeof(Program).GetProperties()
.SelectMany(p => p.GetCustomAttributes(true)
.OfType<ImportParameter>()
.Select(x => new { p.Name, x.Required }))
.ToList();
required.ForEach(x => Console.WriteLine("PropertyName: " + x.Name + " - Required: " + x.Required));
}
}
public class ImportParameter : System.Attribute
{
public Boolean Required {get; private set;}
public ImportParameter(Boolean required)
{
this.Required = required;
}
}
public class Foo
{
public String Test = "Test";
}
'required'请参见ms是一个领域,而不是一个财产。 –