Why doesn't C# infer my generic types?

后端 未结 7 1820
小鲜肉
小鲜肉 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 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 query, out TResult result)
             where TQuery : IQuery;
    }
    
    class Test
    {
        void Test(IQueryProcessor p)
        {
            var query = new SomeQuery();
    
            // Instead of
            // string result = p.Process(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'.

提交回复
热议问题