The type arguments for method cannot be inferred from the usage

前端 未结 6 1714
盖世英雄少女心
盖世英雄少女心 2020-12-05 04:16

Maybe I\'m overworked, but this isn\'t compiling (CS0411). Why?

interface ISignatur
{
    Type Type { get; }
}

interface IAccess where          


        
6条回答
  •  情深已故
    2020-12-05 04:48

    Kirk's answer is right on. As a rule, you're not going to have any luck with type inference when your method signature has fewer types of parameters than it has generic type parameters.

    In your particular case, it seems you could possibly move the T type parameter to the class level and then get type inference on your Get method:

    class ServiceGate
    {
        public IAccess Get(S sig) where S : ISignatur
        {
            throw new NotImplementedException();
        }
    }
    

    Then the code you posted with the CS0411 error could be rewritten as:

    static void Main()
    {
        // Notice: a bit more cumbersome to write here...
        ServiceGate service = new ServiceGate();
    
        // ...but at least you get type inference here.
        IAccess access = service.Get(new Signatur());
    }
    

提交回复
热议问题