简体   繁体   中英

How to group generic constraints?

I'm trying to specify constraint groups to a generic method, but I'm not sure that this is even possible in C#. If it is, I'm having trouble figuring out the syntax. Currently I have the following:

public TOut GetResponse<TOut, TIn>(TIn message)
    where TOut : BaseMessageResponse
    where TIn  : BaseMessageRequest

Which functions perfectly well. However I don't actually send or receive base class messages, I have derived classes instead. What I really want is to be able to declare groups so that I can tell at compile time if I have a mismatched request and response type. So what I want would be something like this:

public TOut GetResponse<TOut, TIn>(TIn message)
    (where TOut : Derived1Response
    where TIn : Derived1Request)
    (where TOut : Derived2Response
    where TIn : Derived2Request)

Is this something that can be done in a single method definition?

There is another solution, which is to have a method definition for each of the pairs of request/response objects, and have each of those call the common generic method I have now, like so:

public Derived1Response GetResponse(Derived1Request request)
{
    return GetResponse<Derived1Response, Derived1Request>(request);
}

public Derived2Response GetResponse(Derived2Request request)
{
    return GetResponse<Derived2Response, Derived2Request>(request);
}

This would bloat the code however, which defeats the purpose of using generics to begin with.

If it were me, I would move the generic definition out to the class level and use separate instances for the different request/response types.

eg

public myClass<TOut, TIn>
    where TOut : BaseMessageResponse
    where TIn  : BaseMessageRequest
{
    public TOut GetResponse(TIn)
    {
        ...
    }
}

Then use:

var derived1Processing = new myClass<Derived1Response, Derived1Request>();
var derived2Processing = new myClass<Derived2Response, Derived2Request>();

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