How to get generic type definition for CRTP type

前端 未结 1 448
心在旅途
心在旅途 2021-01-19 03:06

Given the following CRTP type in C#:

public abstract class DataProviderBase
    where TProvider : DataProviderBase { }
         


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-01-19 04:00

    I think this is actually a very good question. I didn't find a better workaround for this. You can slightly simplify your workaround by using typedefof like this:

    let typeDef = typedefof>
    

    TECHNICAL DETAILS

    The problem is that F#'s typedefof<'T> is just an ordinary function that takes a type argument (unlike typeof in C#, which is an operator). In order to call it, you need to give it an actual type and the function will then call GetGenericTypeDefinition under the cover.

    The reason why typedefof> works is that F# specifies a default type as an argument (in this case obj). In general, F# chooses the less concrete type that matches the constraints. In your case:

    DataProviderBase<_> will become DataProviderBase> and so on.

    Unless you define a new type (as in your workaround), there is no concrete type that could be used as a type argument of typedefof<...>. In this case, the defaulting mechanism simply doesn't work...

    0 讨论(0)
提交回复
热议问题