简体   繁体   English

是否可以在 F# 中为参数化泛型类型定义扩展方法(就像在 C# 中一样)

[英]Is it possible to define extension methods for parameterized generic types in F# (like in C#)

In C# I can define an extension method that applies only to parameterized generic types :在 C# 中,我可以定义一个仅适用于参数化泛型类型的扩展方法:

public static bool fun(this List<int> coll, int x)
{
    return coll.Contains(x);
}

I tried the same in F# but found no way to do so:我在 F# 中尝试了同样的方法,但发现没有办法这样做:

type List<'k when 'k :> int32> with
    member o.x s = o.Contains s

This raises Error FS0660: This code is less generic than required by its annotations because the explicit type variable 'k' could not be generalized.这会引发错误 FS0660:此代码的通用性低于其注释所要求的,因为无法泛化显式类型变量“k”。 It was constrained to be 'int32'.它被限制为“int32”。

It certainly is possible to define a generic extension method like当然可以定义一个通用的扩展方法,比如

type List<'k> with
    member o.x s = o.Contains s

and on a side note to make that extension method available in C#. But that is not the question here.并附注使该扩展方法在 C# 中可用。但这不是这里的问题。 i am concerned about a parameterized generic function. Which I believe is possible to declare only in C# but not in F#.我担心参数化泛型 function。我相信它只能在 C# 中声明,但不能在 F# 中声明。

I conclude that in C# extension methods are functions while in F# the similar concept is implemented as type extensions and parameterized generics are no types, so this is not possible.我得出结论,在 C# 中,扩展方法是函数,而在 F# 中,类似的概念是作为类型扩展实现的,而参数化的 generics 是无类型的,所以这是不可能的。

Am I correct that there is no way to do the same in F#?我是否正确,在 F# 中没有办法做同样的事情?

There is a similar question here: Is it possible to define a generic extension method in F#?这里有一个类似的问题: Is it possible to define a generic extension method in F#? but since 11 years have passed I raise the topic again.但11年过去了,我再次提出这个话题。

F# has a mechanism for defining extensions that is "C#-compatible", and your use case is specifically called out, check here . F# 具有定义“C# 兼容”扩展的机制,并且您的用例被特别调出,请查看此处

Something like this should work:这样的事情应该有效:

open System.Collections.Generic
open System.Runtime.CompilerServices

[<Extension>]
type Extensions =
    [<Extension>]
    static member inline ContainsTest(xs: List<int>, s: int) = 
        xs.Contains(s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM