F#学习:类型的定义和使用语法

代码:

// 定义一个类
type Person = 
    // 属性定义
    { Name: string; Age: int }

    // 静态属性
    static member Tom = { Name = "Tom"; Age = 20 }

    // 静态方法
    static member GetPerson(name, age) = { Name = name; Age = age }

    // 成员方法
    member s.SayHi() = printfn "Hi there, I'm %s and I'm %d years old." s.Name s.Age

// 实例化
let jack = { Name = "Jack"; Age = 30 }

let tom = Person.Tom

// 调用成员方法
jack.SayHi()
tom.SayHi()

// 访问属性
printfn "%s" jack.Name
printfn "%d" tom.Age

输出:

Hi there, I'm Jack and I'm 30 years old.
Hi there, I'm Tom and I'm 20 years old.
Jack
20

type Person =
  {Name: string;
   Age: int;}
  with
    member SayHi : unit -> unit
    static member GetPerson : name:string * age:int -> Person
    static member Tom : Person
  end
val jack : Person = {Name = "Jack";
                     Age = 30;}
val tom : Person = {Name = "Tom";
                    Age = 20;}

用 Reflector 反编译生成的 dll, 代码如下:

[Serializable, CompilationMapping(SourceConstructFlags.RecordType)]
public sealed class Person : IEquatable<Program.Person>, IStructuralEquatable, IComparable<Program.Person>, IComparable, IStructuralComparable
{
    // Fields
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    internal int Age@;
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    internal string Name@;

    // Methods
    public Person(string name, int age);
    [CompilerGenerated]
    public sealed override int CompareTo(Program.Person obj);
    [CompilerGenerated]
    public sealed override int CompareTo(object obj);
    [CompilerGenerated]
    public sealed override int CompareTo(object obj, IComparer comp);
    [CompilerGenerated]
    public sealed override bool Equals(Program.Person obj);
    [CompilerGenerated]
    public sealed override bool Equals(object obj);
    [CompilerGenerated]
    public sealed override bool Equals(object obj, IEqualityComparer comp);
    [CompilerGenerated]
    public sealed override int GetHashCode();
    [CompilerGenerated]
    public sealed override int GetHashCode(IEqualityComparer comp);
    public static Program.Person GetPerson(string name, int age);
    public void SayHi();

    // Properties
    [CompilationMapping(SourceConstructFlags.Field, 1)]
    public int Age { get; }
    [CompilationMapping(SourceConstructFlags.Field, 0)]
    public string Name { get; }
    public static Program.Person Tom { get; }
}

 

 

posted on 2010-07-27 19:05  NeilChen  阅读(575)  评论(0编辑  收藏  举报

导航