C# - 使用Linq获取属性的特性值

3

我有一个具有自身属性的属性。我想访问其中一个属性(布尔值)并检查它是否为真。我能够检查属性是否设置,但至少使用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();

我尝试了一下,但似乎无法验证是否设置了所需属性。


"required" 似乎是一个字段,而不是一个属性。 - Yacoub Massad
2个回答

4

首先,如果您想访问所需的字段,您需要将其公开,最好是一个公共属性:

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();

2
你需要将所需的属性公开,例如:
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";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接