inheritance - F#中的类型继承

标签 inheritance f# c#-to-f#

我找不到正确的语法来编码继承基类 B(用 C# 编写)和他的构造函数而不是基类隐式构造函数的类型 D:

C#代码:

public class B
{
    private int _i;
    private float _f;
    public B()
    {
        _i = 0;
        _f = 0.0f;
    }
    public B(int i)
    {
        _i = 0;
        _f = 0.0f;
    }
    public B(int i, float f)
    {
        _i = i;
        _f = f;
    }
}

F#代码:
type D() =
    inherit B()
    //how to inherit from other constructors ?

谢谢

最佳答案

我找到了一种方法,谢谢这个 blog !

type D =
    class
        inherit B

        new () = {
            inherit B()
        }
        new (i : int) = {
            inherit B(i)
        }
        new ((i,f) : int*single) = {
            inherit B(i, f)
        }
    end

是的,这有点麻烦,但就像布莱恩所说的那样,这不是大多数情况。

编辑:
实际上, class/end 关键字不是强制性的(所以我收回我所说的繁琐)。
正如布赖恩在他的博客中所说 here , F# 通常会推断所定义的类型,从而使这些标记变得不必要/冗余。
type D =
    inherit B

    new () = {
        inherit B()
    }
    new (i : int) = {
        inherit B(i)
    }
    new ((i,f) : int*single) = {
        inherit B(i, f)
    }

关于inheritance - F#中的类型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1619567/

相关文章:

类的 C++ 函数重载

f# - Deedle 系列索引中的重复键

f# - 为什么 Microsoft.FSharp.Quotations.Patterns 中的模式是双引号的?

c# - 如何为 FsCheck 测试生成空字符串

C++设计——网络数据包和序列化

python - 为什么 Visual Studio Code 将 "return super().__init__(self)"插入到派生类中?

.net - 代码引用: how to access variables of a lambda function internally?

map - 方法链 vs |> 管道操作符

f# - 如何从 F# 中的任务编写 SelectMany

c++ - 跟踪 C++ 中父类(super class)有多少个派生类的最佳方法是什么?