English 中文(简体)
1. 严格分类准则推广方法
原标题:Strongly typed LINQ extension methods

I have noticed that all of the Linq extension methods Where, Any, Take etc. all return IEnumerable. For my application it would be a lot nicer if these returned an instance of the same type as the one I am calling on.

例如,如果我打电话到myList.Where(......)LinkedList ,我将在上查阅<>LinkedList 。 i 类似于<代码>List。

当我有类似类型时,这种情况就更加令人痛心。

class MyType
{
    public string MyField;
}

class MyCollection : List<MyType>
{
    // Some useful stuff in here
}

in which case I would like to be able to do

MyCollection source = .......
MyCollection filtered = source.Where(obj => obj.MyField != null);

可悲的是,这从箱子中赢得了一定的工作。 然而,我已经接近尾声,使用了以下法典:

public static ListType Filtered<ListType, ElementType>(this ListType @this, Predicate<ElementType> filter) where ListType : class, ICollection<ElementType>, new()
{
    // Arguments checks omitted

    // Create return instance
    var filtered = new ListType();

    // Apply filter for each element
    foreach (var item in @this)
    {
        if (filter(item))
            filtered.Add(item);
    }

    return filtered;
}

我可以这样做(注意到名列首的代表)。

MyCollection source = .......
MyCollection filtered = source.Filtered((MyType obj) => obj.MyField != null);

因此,我的问题是:为什么我需要以下两个一般性论点:Filter<ListType, ElementType>, 当我具体指明了 where ListType : ICollection<ElementType>? 我的理解是,我无法在“的<>条/代码>中使用任何通用的类型,因为我在方法申报中添加了这种类型,但为何如此? 我是否忽略了这样做的恶果?

最佳回答

确实,你需要两种参数,因为你会发现两种类型:收集类型和元件类型。 不用说,它就是为了执行<条码> IFoo<T>>, ~>>>> 某种<条码> ,但我们不注意<条码>的内容。 T。

页: 1 (如果采用这种方法的话,将更容易理解。) NET 命名公约,将其称为TCollectionTElement

http://www.un.org/Depts/DGACM/index_french.htm ListType。

很难看出,你将如何表达这一“<>无>/>两种类型参数。 鉴于这种推论,请您 查询<>。 在没有明确的情况下,我不清楚为什么这是一个问题。

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...