Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing generic interface that takes a generic interface as a parameter

Tags:

c#

.net

generics

I have these two interfaces

    /// <summary>
///     Represents an interface that knows how one type can be transformed into another type.
/// </summary>
/// <typeparam name="TInput"></typeparam>
/// <typeparam name="TOutput"></typeparam>
public interface ITransformer<in TInput,out TOutput>
{
    TOutput Transform(TInput input);
}

public interface ITransform
{
    TOutput Transform<TInput,TOutput>(ITransformer<TInput, TOutput> transformer);
}

I have a class in which in want to implement ITranform like this.

public class MessageLogs :ITransform
{
    // But I am am not able to implement the ITransform interface like this
   // MessageLogs is getting binded in the param but not getting binded to
  // TInput in the Transform<TIn,TOut>  
   // 
    public T Transform<MessageLogs, T>(ITransformer<MessageLogs, T> transformer)
    {
        return transformer.Transform(this);
    } 

}

How to do it correctly without losing the Genericness of the two interfaces? I have many tranformers.

like image 315
Sameer Avatar asked Sep 21 '15 10:09

Sameer


1 Answers

The interface requires the implemented method to be generic in both TInput and TOutput. In other words, MessageLogs must be able to accept other types for TInput as well. That's not what you want. You're going to need something like:

public interface ITransformer<in TInput,out TOutput>
{
    TOutput Transform(TInput input);
}

public interface ITransform<TInput>
{
    TOutput Transform<TOutput>(ITransformer<TInput, TOutput> transformer);
}

public class MessageLogs : ITransform<MessageLogs>
{
    public TOutput Transform<TOutput>(ITransformer<MessageLogs, TOutput> transformer)
    {
        return transformer.Transform(this);
    }
}
like image 189
Dennis_E Avatar answered Nov 10 '22 00:11

Dennis_E