Why generic extension method with constraint is not recognized as extension method? [duplicate]

只愿长相守 提交于 2019-12-01 06:06:00
Eric Lippert

Method type inference does not take constraints into account when making inferences.

This same question was asked yesterday. See my answer there for more details.

No type inference with generic extension method

I don't think the problem is that the second CAN'T be called, but that IntelliSense won't see it because it can't easily infer the second generic type parameter V from your call without explicit help.

For example, given your two extension methods, the following are all legal

    // IEnumerable<IEnumerable<int>> definition...
    List<List<int>> x = ...;

    // calls your first method (implicitly)
    x.Merge();

    // also calls your first method (explicitly)
    x.Merge<int>();

    // calls your second method (explicitly)
    x.Merge<List<int>, int>();

All three of these compile successfully, I just think with the two generic type parameters, it can't infer your second generic type parameter from usage and thus it's not showing in intellisense, but still legal...

UPDATE: As per the asker, it's not that the two methods were declared as overloads, but that they were either/or. Given that reason Merge() doesn't work on the 2nd form because the relationship between T and V are defined in the type constraints, and thus are not used for type inference as Eric stated in his S.O. answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!