Extension methods on basic common interfaces

I implement a smooth builder pattern that requires the adoption of enumerations in the static extension method and iterates through its contents when applying the functor to the enumerated contents. As in (not the actual code, just an illustration):

public static IValidator<IEnumerable<T>> Each<T>(
    this IValidator<IEnumerable<T>> enumerable, 
    Func<T, bool> action)
{
    foreach (T value in enumerable)
        action(value);

    return validator;
}

This works well for enums, but not for inherited types / interfaces. Let them talk:

IValidator<IEnumerable<Guid>> validator = ...;

IEnumerable<Guid> guids = ...;
validator.Each(guids, guid => guid != Guid.Empty);   // ok

IList<Guid> guids = ...;
validator.Each(guids, guid => guid != Guid.Empty);   // doesn't compile (see below)

The exception is:

IValidator<IList<Guid>>does not contain a definition for "Everyone" and no extension method "Everyone" that takes the first type argument IValidator<IList<Guid>>can be found (if you do not use directives or assembly references?

IValidator<T> , , T. IValidator<IEnumerable<T>> IValidator<IList<T>>? , , IList<T> IEnumerable<T> ( T).

T : IEnumerable<R> , (T R), , .

? ? .

+5
2

IValidator<T>. - :

public interface IValidator<T>

:

public interface IValidator<out T>

, , IValidator<T2> IValidator<T>, , T2 T.

IList<T> IEnumerable<T>, T . IValidator<T> .

, IValidator<T>, T , .

, Each:

public static IValidator<T> Each<T, TValue>(
    this IValidator<T> enumerable, 
    Func<TValue, bool> action) where T : IEnumerable<TValue>
{
    foreach (TValue value in enumerable)
        action(value);

    return validator;
}

, T IEnumerable<TValue>.

+6

:

  • where T: IEnumerable<T>, .

  • IValidator<IEnumerable<T>> IValidator<IList<T>>, . v4, # , . . out Generic Modifier

- , , ..

, , . # 4, , ; , ( ). , .

+2

All Articles