I have a bunch of classes and I want to group them functionally leveraging generics.
Below are my interface and classes:
public interface IMessagePoster<TReceiptType>
{
TReceiptType postMessage(Message message);
}
public class FacebookPoster : IMessagePoster<FacebookReturnType> {}
public class TwitterPoster : IMessagePoster<TwitterReturnType> {}
public class InstagramPoster : IMessagePoster<InstagramReturnType> {}
I now am interested in creating a generic handler class that is able to return the appropriate return type based on the generic type provided.
public class SocialPostHandler<TSocialType, TPostReturnType>
where TSocialType: IMessagePoster<TPostReturnType>, new()
{
public TPostReturnType postMessage(Message message) => new SocialType().postMessage(message);
}
When I call it I have to pass in the class type as well as return type.
new SocialPostHandler<FacebookPoster, FacebookReturnType>(message);
Is there a better way to achieve this generic handler SocialPostHandler
? Anything that would help me infer the type somehow would also help. Thanks!
Aucun commentaire:
Enregistrer un commentaire