繁体   English   中英

必须在非泛型静态类中定义扩展方法

[英]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;
                }
            }
        }
    }
}

当我编译这段代码时,我得到了错误

必须在非泛型静态类中定义扩展方法。

我的问题是

  1. 我无法将此分类更改为静态。 没有它,我将如何做到这一点?

添加新的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.

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