• F#基本类型——Class


    F#的class赋予了F#面向对象的编程能力,也是F#连接.net中其它面向对象语言的桥梁。其基本形式如下:

    // Class definition:
    type [access-modifier] type-name [type-params]( parameter-list ) [ as identifier ] =
         [ class ]
             [ inherit base-type-name(base-constructor-args) ]
             [ let-bindings ]
             [ do-bindings ]
             member-list
             ...
         [ end ]
    // Mutually recursive class definitions:
    type [access-modifier] type-name1 ...
    and [access-modifier] type-name2 ...
    ...

    构造函数

    首先我们来通过一个简单的示例来介绍F#中的构造函数:
        type Point(x:int,y:int) =
            new() = Point(0,0)
            new(x:int) = Point(x,0)

    它的类型为:
        type Point =
            class
                new : unit -> Point
                new : x:int -> Point
                new : x:int * y:int –> Point
            end

    从中可以看出,这三行分别定义了三个构造函数,首先第一行type Point(x:int,y:int)定义了一个初始的构造函数,它是所有其它构造函数的入口。

    第二行new()和第三行new(x:int)分别基于初始构造函数定义了两个新的构造函数,这个Point类的等效C#代码为:
        public class Point
        {
            public Point() : this(0, 0) { }
            public Point(int x) : this(x, 0) { }
            public Point(int x, int y) { }
        }

    初始化:

    进入构造函数后,我们第一步要做的是初始化,初始化工作一般是通过do绑定来完成的,我们把上面那个Point类改造一下,在构造函数中加入一个打印x和y值的功能:

        type Point(x:int,y:int) =
             do
                 printfn "(%d,%d)" x y
             new() = Point(0,0)
             new(x:int) = Point(x,0)

    do绑定可以看做是在初始构造函数的函数体,也就是说,其它所有的构造函数都会执行do绑定的表达式。

    另外,如果要实现更复杂的初始化操作,还牵涉到了let绑定,关于let绑定和do绑定更多信息,在后续介绍F#对象中的成员时再做进一步介绍。

    基类

    在F#中,通过关键字inherit指明了对象的基类,这一点其实和C#很相似,只是语法结构不一样,这里只举一个简单的例子,后续介绍F#对象的继承时再做详细介绍。

        type MyClassBase1() =
             let mutable z = 0
             abstract member function1 : int –> int
             default u.function1(a : int) = z <- z + a; z

       type MyClassDerived1() =
            inherit MyClassBase1()
            override u.function1(a: int) = a + 1

    自标示符(Self Identifiers)

    在C#和C++中,可以通过this关键字引用当前对象实例的成员;但在F#中,这种标示自己的标示符并不是特定的,可以通过as来生命为任意一个名称,示例如下:

        type MyClass2(data_in) as self =
             let data = data_in
             do
                 self.PrintMessage()
             member this.PrintMessage() =
                 printf "Creating MyClass2 with Data %d" data

    成员

    F#对象的成员非常丰富,总体来说大致有如下几种:

    1. let绑定
    2. do绑定
    3. 成员变量
    4. 属性
    5. 索引
    6. 方法
    7. 运算符重载
    8. 事件

    由于牵涉面较大,这里就不介绍了,后续再单独写文章介绍这部分内容。

  • 相关阅读:
    INI配置文件的格式
    UserControl图片显示报错问题
    CornerRadius圆角属性
    Stretch属性
    [WPF]The type name ‘App’ does not exist in the type '...'的问题
    [Word]解决Word中执行输入操作时后面字符自动被删除的问题
    MATLAB中的取整函数(fix、round、floor、ceil)
    [数据库][C#]几个常用的正则表达式
    [数据库][C#]提取字符串中的数字
    springmvc注解知识点汇总
  • 原文地址:https://www.cnblogs.com/TianFang/p/1655354.html
Copyright © 2020-2023  润新知