gpt4 book ai didi

c# - F# 2.0 中的错误与泛型类型参数的约束在哪里有关?

转载 作者:行者123 更新时间:2023-11-30 17:10:36 26 4
gpt4 key购买 nike

如果我有一个要从 F# 使用的 C# 方法并接收两个类型化参数,如下所示:

public class Foo
{
public static void GenericMethodWithTwoTypeParamsThatHaveAWhereClass<TA, TB>() where TA : TB
{

}
}

当我尝试通过 F# 调用它时,编译器会报错:

Foo.GenericMethodWithTwoTypeParamsThatHaveAWhereClass<System.IO.BinaryWriter, System.IDisposable>()

那么,这是 F# 2.0 中的错误吗?

最佳答案

F# 不支持这种类型的约束。 spec指示 t1 :> t2 形式的约束被视为 t1 = t2,这解释了您的错误:

This expression was expected to have type BinaryWriter but here has type System.IDisposable

根据 TB 的使用方式,您可能可以通过

GenericMethodWithTwoTypeParamsThatHaveAWhereClass<BinaryWriter, _>()
根据上述规则,

TB 将被推断为 BinaryWriter。但是,如果这可行,那么您的 C# 方法可能只需要一个类型参数。

关于c# - F# 2.0 中的错误与泛型类型参数的约束在哪里有关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12040537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com