简体   繁体   English

当OfType在C#中不可用时如何获取特定的自定义属性?

[英]How to obtain a specific custom attribute when OfType is not available in C#?

In my application I'm trying to obtain a specific attribute using a foreach loop:在我的应用程序中,我试图使用 foreach 循环获取特定属性:

Datasource of foreach: foreach的数据源:

在此处输入图片说明

Now I'd like to check for each property if it has the "EditTemplate" CustomAttribute, and if the property has it, put this attribute in a variable like this:现在我想检查每个属性是否具有“EditTemplate”CustomAttribute,如果该属性具有,则将此属性放入如下变量中:

在此处输入图片说明

Foreach: Foreach:

@foreach (var property in EditObject.GetType().GetProperties())
{
      var attributes = property.GetCustomAttributes(true);
      var DoSomeAttribute = attributes;

      //THIS IS THE PART THAT DOES NOT WORK BECAUSE .OfType is not recognized
      //var attribute = property.GetCustomAttributes(true).OfType<EditTemplateAttribute>().FirstOrDefault();
}

The line of code "var attributes = property.GetCustomAttributes(true)" giving me an object with x amount of items(Attributes within):代码行“var attributes = property.GetCustomAttributes(true)”给了我一个包含 x 个项目(属性内)的对象:

在此处输入图片说明

Now this is where I want to do a check if the attribute is of Type "EditTemplateAttribute", if this is the case I want to put it in a variable like this:现在这是我要检查属性是否属于“EditTemplateAttribute”类型的地方,如果是这种情况,我想将其放入这样的变量中:

在此处输入图片说明

In another piece of code(and another foreach) I achieved this by:在另一段代码(和另一个 foreach)中,我通过以下方式实现了这一点:

var attribute = property.GetCustomAttributes(true).OfType<EditTemplateAttribute>().FirstOrDefault();

However the .OfType is not available here.但是 .OfType 在这里不可用。

Does anyone know how to achieve this?有谁知道如何实现这一目标?

Thanks in advance!提前致谢!

I don't know why .OfType should be unavailable.我不知道为什么 .OfType 应该不可用。 Try adding using System.Linq .尝试using System.Linq添加。 This is the namespace where OfType extension method is defined.这是定义 OfType 扩展方法的命名空间。

I've noticed that your foreach is prefixed with '@'.我注意到您的 foreach 以“@”为前缀。 Are you using MVC Razor view?你在使用 MVC Razor 视图吗? In that case you can add using like: @using System.Linq在这种情况下,您可以使用如下添加: @using System.Linq

In any case you can replace .OfType<EditTemplateAttribute>() with:在任何情况下,您都可以将.OfType<EditTemplateAttribute>()替换为:

.Where(x => x is EditTemplateAttribute).Select(x => (EditTemplateAttribute)x)

Or you can use (may return attribute instance or null):或者您可以使用(可能返回属性实例或 null):

var someAttribute = (EditTemplateAttribute)attributes.FirstOrDefault(x => x is EditTemplateAttribute);

Or, you can write your own OfType extension method (and use it like you wanted at first):或者,您可以编写自己的 OfType 扩展方法(并按照您的意愿使用它):

public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
{
  foreach (object obj in source)
  {
    if (obj is TResult)
      yield return (TResult) obj;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM