简体   繁体   中英

Inferring generic parameter type from a callback function

I have a piece of code that currently looks like this:

Signature of the Subscribe method:

void Subscribe<T, TResult>(Func<T, TResult> action);

class Service { 
   int methodThatRequiresIntAndReturnsInt(int i) => i * 2;
}

In my mind it should be possible to extrapolate what the types for T and TReturn when trying to use the subscribe method, however compiler tells me that the types cannot be inferred from usage, meaning i end up writing this code:

Queue.Subscribe<int, int>(Service.methodThatRequiresIntAndReturnsInt);

My question is whether it is possible and if so how should the method signature/usage look so that it would be possible to use it without type hinting eg:

Queue.Subscribe(input => input * 2);

Current implementation is along the lines of this:

_commandSubscription.Subscribe<CreateUpdateCommand, bool>(Resolve<UpdateService>().CreateUpdate);
_commandSubscription.Subscribe<AddCommentCommand>(Resolve<UpdateService>().AddComment);

The implementations for the service methods are as follows:

public class UpdateService {

    public void AddComment(AddCommentCommand command) {
         // DO STUFF
    }

    public bool CreateUpdate(CreateUpdateCommand command) {
        // Do stuff 
        return true;
    }

}

You could do the following:

Queue.Subscribe((int i) => Service.methodThatRequiresIntAndReturnsInt(i));

In practice the subcribed function works equivalently and you avoid explicitly typing all generic arguments.

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