[英]Extension method must be defined in a non-generic static class
我在网络表单中有这个代码:
namespace TrendsTwitterati
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<TweetEntity> tweetEntity = tt.GetTweetEntity(1, "")
.DistinctBy(e => e.EntityPicURL);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
}
当我编译这段代码时,我得到了错误
必须在非泛型静态类中定义扩展方法。
我的问题是
添加新的static
类并在其中定义扩展方法。 查看扩展方法的MSDN文档 。
namespace TrendsTwitterati
{
public partial class Default: System.Web.UI.Page
{
}
public static class MyExtensions
{
public static IEnumerable < TSource > DistinctBy < TSource, TKey > (this IEnumerable < TSource > source, Func < TSource, TKey > keySelector)
{
HashSet < TKey > seenKeys = new HashSet < TKey > ();
foreach(TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield
return element;
}
}
}
}
}
以这种方式将您的方法添加到扩展方法的static
类中
namespace TrendsTwitterati
{
public static class Extension
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
}
现在用它
namespace TrendsTwitterati
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<TweetEntity> tweetEntity = tt.GetTweetEntity(1, "").DistinctBy(e => e.EntityPicURL);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.