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

问题描述

在我的应用程序中,我试图使用foreach循环获取特定属性:

foreach的数据源:

enter image description here

现在,我想检查每个属性是否具有“ EditTemplate” CustomAttribute,如果该属性具有,请将此属性放在这样的变量中:

enter image description here

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

代码行“ var attributes = property.GetCustomAttributes(true)”为我提供了一个对象,其中包含x项(属性在其中):

enter image description here

现在这是我要检查属性是否为“ EditTemplateAttribute”类型的地方,如果是这种情况,我想将其放入这样的变量中:

enter image description here

在另一段代码(和另一个foreach)中,我通过以下方式实现了这一目标:

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

但是.OfType在这里不可用。

有人知道如何实现这一目标吗?

谢谢!

解决方法

我不知道为什么.OfType不可用。 尝试添加using System.Linq。这是定义OfType扩展方法的名称空间。

我注意到您的foreach前缀为“ @”。您正在使用MVC Razor视图吗? 在这种情况下,您可以使用以下命令添加:@using System.Linq

在任何情况下,您都可以将.OfType<EditTemplateAttribute>()替换为:

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

或者您可以使用(可以返回属性实例或null):

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

或者,您可以编写自己的OfType扩展方法(并像开始时一样使用它):

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...