簡體   English   中英

C# - 使用Linq獲取屬性

[英]C# - Get property of Attribute with Linq

我有一個屬性,它有自己的屬性。 我想訪問其中一個屬性(布爾值)並檢查它是否為真。 我能夠檢查屬性是否已設置,但這是關於所有...至少與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搜索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();

您必須公開所需的財產,例如

public class ImportParameter : System.Attribute
{
  public Boolean Required {get; private set;}

  public ImportParameter(Boolean required)
  {
      this.Required = required;
  }
}

現在您應該能夠訪問您的屬性對象。

請注意,通過使用public <DataType> <Name> {get; private set;} 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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM