C#-使用Linq获取Attribute的属性 [英] C# - Get property of Attribute with Linq

查看:370
本文介绍了C#-使用Linq获取Attribute的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个本身具有属性的属性.我想访问这些属性之一(一个布尔值),并检查其是否正确.我能够检查是否设置了Attribute,但这至少与linq有关.

I have a Attribute which has properties itself. I would like to access one of These properties (a boolean) and check whether it's true or not. I was able to check whether the Attribute is set, but thats about all .. at least with linq.

属性:

public class ImportParameter : System.Attribute
{
    private Boolean required;

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

示例:

    [ImportParameter(false)]
    public long AufgabeOID { get; set; }

到目前为止我所拥有的:

What I have so far:

        var properties = type.GetProperties()
            .Where(p => Attribute.IsDefined(p, typeof(ImportParameter)))
            .Select(p => p.Name).ToList();

我玩了一点,但似乎无法验证是否设置了所需的属性.

I played around a Little, but I don't seem to be able to verify whether the property required is set or not.

推荐答案

首先,如果要访问必填字段,则需要将该字段设为公开,最好是公开属性:

First of all if you want to access the required field you need to make it public, better a public property:

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

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

然后,您可以使用此查询Linq搜索将Required属性设置为false的属性:

then you can use this query Linq to search for properties that have the Required attribute set to 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();

这篇关于C#-使用Linq获取Attribute的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆