This article explores the challenges of implementing type inference in C#, focusing on the limitations and potential solutions for partial generic type inference.
The use case described is where an extension method should be available for a specific base class, with generic parameters related to a method argument. However, the extension method should also return a specific type related to the particular descendant that it's invoked upon.
As it turns out, partial generic type inference is not directly supported in C#. However, there are strategies that can achieve a similar result.
Method 1: Using Type Constraints
A syntax similar to the desired code can be achieved using type constraints:
public static TReg Parameter(this TReg p, string name, T value) where TReg : ParameterizedRegistrationBase
This approach requires specifying both generic type arguments during invocation, which may not be desirable in all cases.
Method 2: Using Two Functions with Wrapper
This approach involves splitting the operation into two functions:
public static ThatAreWrapperThat (this IEnumerable source) { return new ThatAreWrapper (source); } public class ThatAreWrapper { // ... Implementation }
And:
listOfFruits.That().Are().Where(banana => banana.Peel != Color.Black)
This workaround requires additional steps, but allows for more flexibility in specifying the result type.
Method 3: Extending the Base Class
By introducing the extension methods directly into the base class, the problem can be avoided. However, this approach removes the ability to use the extension methods on other classes in the future.
Partial generic type inference is not directly supported in C#, but there are workarounds that can provide similar functionality. The specific approach to use depends on the specific requirements and trade-offs involved.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3