Why doesn't C# infer my generic types?

后端 未结 7 1748
小鲜肉
小鲜肉 2020-11-22 16:38

I\'m having lots of Funcy fun (fun intended) with generic methods. In most cases C# type inference is smart enough to find out what generic arguments it must use on my gener

相关标签:
7条回答
  • 2020-11-22 16:54

    I won't go into the why again, I have no illusions of being able to do a better explanation than Eric Lippert.

    However, there is a solution that doesn't require late binding or extra parameters to your method call. It's not super intuitive however, so I'll leave it to the reader to decide if it's an improvement.

    First off, modify IQuery to make it self-referencing:

    public interface IQuery<TQuery, TResult> where TQuery: IQuery<TQuery, TResult>
    {
    }
    

    Your IQueryProcessor would look like this:

    public interface IQueryProcessor
    {
        Task<TResult> ProcessAsync<TQuery, TResult>(IQuery<TQuery, TResult> query)
            where TQuery: IQuery<TQuery, TResult>;
    }
    

    An actual query type:

    public class MyQuery: IQuery<MyQuery, MyResult>
    {
        // Neccessary query parameters
    }
    

    An implementation of the processor might look like:

    public Task<TResult> ProcessAsync<TQuery, TResult>(IQuery<TQuery, TResult> query)
        where TQuery: IQuery<TQuery, TResult>
    {
        var handler = serviceProvider.Resolve<QueryHandler<TQuery, TResult>>();
        // etc.
    }
    
    0 讨论(0)
  • 2020-11-22 16:56

    It doesn't use constraints to infer types. Rather it infers types (when possible) and then checks constraints.

    Therefore, while the only possible TResult that could be used with a SomeQuery parameter, it won't see this.

    Note also, that it would be perfectly possible for SomeQuery to also implement IQuery<int>, which is one reason why this is limitation on the compiler may not be a bad idea.

    0 讨论(0)
  • 2020-11-22 16:59

    Another workaround for this issue is to add additional parameter for type resolution.To avoid changes in existing codebase such parameter can be added to extension method. For instance you can add the following extension method:

    static class QueryProcessorExtension
    {
        public static TResult Process<TQuery, TResult>(
            this IQueryProcessor processor, TQuery query,
            //Additional parameter for TQuery -> IQuery<TResult> type resolution:
            Func<TQuery, IQuery<TResult>> typeResolver)
            where TQuery : IQuery<TResult>
        {
            return processor.Process<TQuery, TResult>(query);
        }
    }
    

    Now we can use this extension as follows:

    void Test(IQueryProcessor p)
    {
        var query = new SomeQuery();
    
        //You can now call it like this:
        p.Process(query, x => x);
        //Instead of
        p.Process<SomeQuery, string>(query);
    }
    

    Which is far from ideal but much better than providing types explicitly.

    P.S. Related links for this issue in dotnet repository:

    https://github.com/dotnet/csharplang/issues/997

    https://github.com/dotnet/roslyn/pull/7850

    0 讨论(0)
  • 2020-11-22 17:00

    A bunch of people have pointed out that C# does not make inferences based on constraints. That is correct, and relevant to the question. Inferences are made by examining arguments and their corresponding formal parameter types and that is the only source of inference information.

    A bunch of people have then linked to this article:

    http://blogs.msdn.com/b/ericlippert/archive/2007/11/05/c-3-0-return-type-inference-does-not-work-on-member-groups.aspx

    That article is both out-of-date and irrelevant to the question. It is out-of-date because it describes a design decision we made in C# 3.0 which we then reversed in C# 4.0, mostly based on the response to that article. I've just added an update to that effect to the article.

    It is irrelevant because the article is about return type inference from method group arguments to generic delegate formal parameters. That is not the situation the original poster asks about.

    The relevant article of mine to read is rather this one:

    http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

    UPDATE: I have heard news that C# 7.3 has slightly changed the rules for when constraints are applied, making the above ten-year-old article no longer accurate. When I have time I'll review the changes my former colleagues have made and see if it is worthwhile to post a correction on my new blog; until then, use caution and see what C# 7.3 does in practice.

    0 讨论(0)
  • 2020-11-22 17:02

    The why has been well answered but there is an alternative solution. I face the same issues regularly however dynamic or any solution using reflection or allocating data is out of question in my case (joy of video games...)

    So instead I pass the return as an out parameters which is then correctly inferred.

    interface IQueryProcessor
    {
         void Process<TQuery, TResult>(TQuery query, out TResult result)
             where TQuery : IQuery<TResult>;
    }
    
    class Test
    {
        void Test(IQueryProcessor p)
        {
            var query = new SomeQuery();
    
            // Instead of
            // string result = p.Process<SomeQuery, string>(query);
    
            // You write
            string result;
            p.Process(query, out result);
        }
    }
    

    The only drawback I can think of is that it's prohibiting usage of 'var'.

    0 讨论(0)
  • 2020-11-22 17:06

    The spec lays this out pretty clearly:

    Section 7.4.2 Type Inference

    If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature:

    Tr M(T1 x1 … Tm xm)

    With a method call of the form M(E1 …Em) the task of type inference is to find unique type arguments S1…Sn for each of the type parameters X1…Xn so that the call M(E1…Em)becomes valid.

    As you can see, the return type is not used for type inference. If the method call does not map directly to the type arguments inference immediately fails.

    The compiler does not just assume that you wanted string as the TResult argument, nor can it. Imagine a TResult derived from string. Both would be valid, so which to choose? Better to be explicit.

    0 讨论(0)
提交回复
热议问题