Why doesn't C# do “simple” type inference on generics?

后端 未结 6 1343
谎友^
谎友^ 2021-01-03 05:45

Just curious: sure, we all know that the general case of type inference for generics is undecidable. And so C# won\'t do any kind of sub-typing at all: if Foo

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 06:04

    The point is that you can't do it for all cases, so you don't do it for any. Where do you draw the line is the problem. If you don't do it for any than everyone who uses C# knows that it doesn't do that. If you do it part of the time, that is when it gets complicated. It can become a guessing game as to how your code will behave. It's all the edge cases on what is easy and what is not that become complex to the programmers and can cause errors in code.

    Here is a scenario that would absolutely cause havoc. Let's say that you can infer boo is bar in scenario A. Someone else comes and changes part of the base type and this no longer holds true. By making it either always apply, or never apply, you don't run into this situation, ever. In a complex environment, tracking down a problem like this can be an absolute nightmare, especially when you factor in this may not be catchable during the compile time (reflection, the DLR etc.). It's so much easier to write code to manually handle the conversion up front, than assume that it will work in your scenario when the possibility that sometime down the line it just won't (not counting upgrading to a new version).

    C# 4.0 does fix some of this as they allowed inference on what they felt is "safe" for the programmers.

提交回复
热议问题