简体   繁体   中英

Extension method for IEnumerable<T> which returns type of -this-

Like I see, most IEnumerable extensions eats IEnumerable and then vomits also IEnumerable. Is it possible to make an extension method, which can eat any IEnumerable (like List) and then return the same type - List?

For example, I want to iterate over collection, if something is wrong, I will throw exception, but if all is OK, I need to return same instance (same type).

You need to use two generic arguments:

public static TEnumerable Foo<TEnumerable, TItem>(this TEnumerable sequence)
    where TEnumerable: IEnumerable<TItem>
{
    return sequence;
}

Note that as a result of this change you're not going to be able to infer the generic arguments when invoking this method; you're going to have to specify them explicitly.

I don't see how doing this could be beneficial, but you can solve the generics part of the problem like this:

public static TEnumerable MyExtensionMethod<T, TEnumerable>(this TEnumerable enumerable)
    where TEnumerable : IEnumerable<T>
{
    ...
}

However, you may find it difficult to actually implement such a thing because there is no generic way to create the TEnumerable you want to return.

For example, I want to iterate over collection, if something is wrong, I will throw exception, but if all is OK, I need to return same instance (same type).

Does the following extension method not accomplish what you really want? I don't understand why you want to return the same instance.

public static void Consume<T>(this IEnumerable<T> enumerable)
{
    foreach (var item in enumerable)
    {
        // Do nothing
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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