简体   繁体   English

如何将扩展方法放在库中?

[英]How to put extension methods in a library?

I wanted to have the removeAll method to remove items in a observableCollection. 我想使用removeAll方法来删除observableCollection中的项目。 The code is: 代码是:

public static class ExtensionMethods
{
    public static int Remove<T>(
        this ObservableCollection<T> coll, Func<T, bool> condition)
    {
        var itemsToRemove = coll.Where(condition).ToList();

        foreach (var itemToRemove in itemsToRemove)
        {
            coll.Remove(itemToRemove);
        }

        return itemsToRemove.Count;
    }
}

I have my main project and I created a new DLL project with utilities related with collections, so I created in this second project a class that has this code. 我有主项目,并创建了一个与集合相关的实用程序的新DLL项目,因此在第二个项目中创建了一个具有此代码的类。

However, I don't have the RemoveAll method in available to the observableCollection, I mean that: 但是,我没有可用于observableCollection的RemoveAll方法,我的意思是:

ObservableCollection<MyType> o = new ObservableCollection<MyType>();
o.RemoveAll ??

Is not available. 不可用。 I add a new reference in my main project to the second project and I include the using of the library. 我在主项目中向第二个项目添加了一个新引用,并且包括了库的使用。

If in my main project I create a class then the method is available. 如果在我的主项目中创建一个类,则该方法可用。 But I would like to have a library with this extension methods to have this methods to another project and not to add a new class in each project. 但是我想拥有一个具有此扩展方法的库,以便将该方法用于另一个项目,而不是在每个项目中添加新类。

The problem is that you did not implement a RemoveAll method, but a Remove<T> method. 问题是您没有实现RemoveAll方法,而是实现了Remove<T>方法。

public static int Remove<T>(this ObservableCollection<T> coll, Func<T, bool> condition)

Maybe if you declare it like this...? 也许如果您这样声明...?

public static int RemoveAll<T>(this ObservableCollection<T> coll, Func<T, bool> condition)

Also, of course you have to reference the DLL in your original project and include the namespace. 另外,当然,您必须在原始项目中引用DLL并包括名称空间。

What strikes me funny is that you say it works when you change the class name from ExtensionMethods to ObservableCollection . 让我感到有趣的是,当您将类名称从ExtensionMethods更改为ObservableCollection时,您说它可以工作。 Could it be that you accidentially created a class named ObservableCollection that now conflicts with System.Collections.Generic.ObservableCollection ? 可能是您意外创建了一个名为ObservableCollection的类,该类现在与System.Collections.Generic.ObservableCollection冲突吗?

You must include the namespace with "using" keyword. 您必须在名称空间中包含“ using”关键字。 For example: 例如:

using System.Collections.Generic;
using System.Linq;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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