Implementing a generic interface that uses a generic interface as a parameter

I have 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 I need to implement ITranform as follows.

 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 right without losing the Genericness of the two interfaces? I have a lot of transformers.

+5
source share
2 answers

The interface requires that the implemented method be common in both TInput and TOutput. In other words, MessageLogs must also accept other types for TInput. This is not what you want. You will 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); } } 
+2
source

Change your interface to a universal interface instead of the method in it

As below

 public interface ITransformer<in TInput, out TOutput> { TOutput Transform(TInput input); } public interface ITransform<TInput, TOutput> { TOutput Transform(ITransformer<TInput, TOutput> transformer); } public class MessageLogs<T> : ITransform<MessageLogs<T>,T> { public T Transform(ITransformer<MessageLogs<T>, T> transformer) { return transformer.Transform(this); } } 

Updated Code Let's say you do not want MessageLog to know what it is turning to. then follow below.

 public class Transformer<T1,T2> : ITransform<T1,T2> { public T2 Transform(T1 logger,ITransformer<T1, T2> transformer) { return transformer.Transform(logger); } } public class MessageLogs { // code specific to message logging } 
+1
source

Source: https://habr.com/ru/post/1231936/


All Articles