f# - 如何在F#中实现抽象类?

标签 f# abstract-class

看完this PDC session 后,我想尝试学习一些F#。因此,我认为最好的方法是用F#重写我已经在C#中完成的操作,但是我的大脑只是拒绝以功能模式进行思考。
我有一个抽象类,它具有一些抽象方法和一些虚拟方法。我也想重写一些虚方法。这个类是用C#编写并编译的,我不打算在F#中重写它。
所以我的问题是:

  • 是否有人提供了有关如何实现抽象类,抽象方法和虚拟方法
  • 的简短示例
  • 我可以重载构造函数吗?
  • 如果我想在dll中编译
  • 并将其提供给基于C#的程序,则
  • 有任何约束。

  • 任何帮助,将不胜感激。

    更新:
    我真的很感谢Brian的回答,但是我仍然不清楚,所以我想澄清一下。让我们假装这是我用C#编写并用dll编译的抽象类。如何在F#中实现它?
    public abstract class MyAbstractClass
    {
        public abstract Person GetFullName(string firstName, string lastName);
    
        public abstract bool TryParse(string fullName, out Person person);
    
        public virtual IEnumerable<Person> GetChildren(Person parent)
        {
            List<Person> kids = new List<Person>();
            foreach(Child person in GroupOfPeople)
            {
                if(person.Parent == parent)
                   kids.Add(child as Person);
            }
            return kids;
        }
    
        public virtual IEnumerable<Child> GroupOfPeople { get; set; }
    }
    

    某些正在寻找F#资源的人员的文档:
    -如果有其他F#有兴趣获得我在Don Syme(F#的创建者)博客free chapters of his book F# Expert上找到的一些文档。您可以下载doc格式的文件。
  • Tomas Petricek编写的“现实世界中的函数编程”具有 free chapter here

  • 其他一些有趣的资源:
  • Scott Hanselman's blog
  • 发布
  • Dustin Campbell's blog
  • Tomas Petricek's blog
  • F#的地方-hubFS
  • F# WIKI
  • Microsoft Research
  • 最佳答案

    这是一些示例代码

    type IBaz =
        abstract member Baz : int -> int
    
    [<AbstractClass>]
    type MyAbsClass() =
        // abstract
        abstract member Foo : int -> int
        // virtual (abstract with default value)
        abstract member Bar : string -> int
        default this.Bar s = s.Length 
        // concrete
        member this.Qux x = x + 1
    
        // a way to implement an interface
        abstract member Baz: int -> int
        interface IBaz with
            member this.Baz x = this.Baz x
    
    type MySubClass(z : int) =
        inherit MyAbsClass()
        override this.Foo x = x + 2
        override this.Bar s = (base.Bar s) - 1
        override this.Baz x = x + 100
        member this.Z = z
        new () = MySubClass(0)
    
    let c = new MySubClass(42)    
    printfn "%d %d %d %d %d" c.Z (c.Foo 40) (c.Bar "two") (c.Qux 41) (c.Baz 42000)
    

    关于f# - 如何在F#中实现抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/310619/

    相关文章:

    c# - ASP.NET MVC F# Controller 操作忽略参数

    inheritance - 我应该使用继承还是接口(interface)?

    c# - C# 中的委托(delegate)和 F# 中作为第一类值的函数有什么区别?

    c# - 为什么不能创建抽象类实例但可以调用其构造函数?

    F#记录构造函数

    f# - 将一级函数参数传递给 LINQ 表达式

    python - 为什么在 Python 中使用抽象基类?

    C++ "' 形状' : cannot instantiate abstract class"can't find the source of the problem

    c++ - 具有静态函数的类在 C++ 中成为抽象基类

    c# - .NET Stream 类是否设计不当?