如何解决当OfType在C#中不可用时,如何获取特定的自定义属性?
在我的应用程序中,我试图使用foreach循环获取特定属性:
foreach的数据源:
现在,我想检查每个属性是否具有“ EditTemplate” CustomAttribute,如果该属性具有,请将此属性放在这样的变量中:
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项(属性在其中):
现在这是我要检查属性是否为“ EditTemplateAttribute”类型的地方,如果是这种情况,我想将其放入这样的变量中:
在另一段代码(和另一个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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。