具有泛型和公共字段的多态 [英] Polymorphism with Generics and common fields

查看:54
本文介绍了具有泛型和公共字段的多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已对此问题进行了回答,但有些相似,但是此问题需要使用泛型,同时将参数类型强制为具有一些公共字段.

Had this question answered and is somewhat similar but this question requires using Generics while enforcing parameter type to have some common fields.

type Document = {
    Name: string
    Version: string
}

let inline requestData<'t> (document: 't) =
    Console.WriteLine(document.Name)
    Console.WriteLine(document.Version)

测试

requestData<Document>({Name = "test"; Version="259723983"})

我得到的错误是

根据此程序点之前的信息查找不确定类型的对象.在此程序指向之前可能需要类型注释,以约束对象的类型.这样可以解决查找问题.

Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constraint the type of the object. This may allow the lookup to be resolved.

修改

let inline requestData<'t> (document: 't) =
    let name = (^document: (member Name: string)(document))

声明的类型参数t'不能在此处使用,因为类型参数不能在编译时解析.

The declared type parameter t' cannot be used here since the type parameter cannot be resolved at compile time.

推荐答案

您需要限制类型,而不是document参数.同样,'T表示法是针对通用泛型的,而不是针对SRTP的.如果您坚持要添加类型参数(不确定原因),则可以通过以下方式进行定义:

You need to constrain on the type not the document parameter. Also, the 'T notation is for the usual generics, not SRTP. If you insist on adding the type parameter (not sure why), this is how you can define it:

let inline requestData< ^a when ^a : (member Name : string)  > x =
    Console.WriteLine(^a: (member Name: string)(x))

这样,您可以这样写:

open System

type Document = {
    Name: string
    Version: string
}

type OtherDoc = {
    Name: string
    Version: string
}

let doc1 = {Document.Name = "Joe"; Version = "123"}
let doc2 = {OtherDoc.Name = "Jim"; Version = "456"}

requestData doc2
requestData doc1

或者:

requestData<Document> doc1 //Joe
requestData<OtherDoc> doc2 //Jim

这将是一个错误:

requestData<Document> doc2 //error FS0001: This expression was expected to have type...

这篇关于具有泛型和公共字段的多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆