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

后端 未结 6 1267
谎友^
谎友^ 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:21

    So, I found an elegant work-around for my real problem (although I do find that C# is overly constraining).

    As you've gathered, my main goal is to write code that can register a callback to a method that you'll write later (in 2011, for example) and that was defined externally with generic type parameters that don't exist today, hence aren't available to me at the time I wrote my library (today).

    For example I need to make a list of objects you'll define next year, and iterate over the elements of the list, calling back to each object's "Aggregate" method. My frustration was that while you can certainly register your class, or an object in your class, C# type checking wasn't letting me call the methods because I don't know the types (I can get the types via GetType() but can't use those as types in expressions). So I was starting to use reflection to hand-compile the desired behavior, which is ugly and can violate type safety.

    And the answer is... anonymous classes. Since an anonymous class is like a closure, I can define my callbacks inside the "register" routine (which has access to the types: you can pass them in when you register your objects). I'll create a little anonymous callback method, right inline, and save a delegate to it. The callback method can call your aggregator since C# considers it to "know" the parameter types. And yet my list can list methods with known type signatures at the time I compile my library, namely tomorrow.

    Very clean and C# doesn't end up driving me insane. Still, C# really doesn't try hard enough to infer subtype relationships (sorry Eric: "what should be subtype relationship"). Generics aren't macros in C. Yet C# is much too close to treating them as if they were!

    And that answers my own (real) question.

提交回复
热议问题