F# generic type constraints and duck typing

后端 未结 3 1055
心在旅途
心在旅途 2020-12-19 00:21

I\'m trying to implement duck typing in F# and I spotted that you can have a member constraint in F# generics as follows:

type ListEntryViewModel<\'T wh         


        
3条回答
  •  猫巷女王i
    2020-12-19 00:52

    To make your original code work:

    type ListEntryViewModel< ^T when ^T : (member Name : string)>(model:^T) = 
        inherit ViewModelBase()
    
        member inline this.Name with get() = (^T : (member Name : string) model)
    

    So you have to mark the member as "inline" and repeat the constraint in the member function.

    I agree with Tomas that an Interface-based approach is usually preferred in F#.

提交回复
热议问题