Linq有这个方便的功能Where
,让我可以过滤可枚举的结果......
foreach (var method in typeof(Program).GetMethods())
{
foreach (var attr in method.GetCustomAttributes(inherit: true).Where(a => a is UrlAttribute))
{
Console.WriteLine(((UrlAttribute)attr).Url);
}
}
但是对于仅检索某种类型的对象似乎并不是很方便,因为我仍然需要强制转换它们。 Linq没有解决这个问题的方法,是吗?
这是一个很好的解决方案吗?
public static class Extensions
{
public static IEnumerable<T> OfType<T>(this IEnumerable<object> e)
{
return e.Where(x => x is T).Cast<T>();
}
}
我正在学习如何编写自己的属性,而我正试图弄清楚如何全部检索它们。
答案 0 :(得分:7)