08 Sep 2008 @ 8:58 上午 
 

来自 hubfs 的回复

 

我在初学 F# 的时候, 对 C# 只能算是一知半解, 甚至可以说是个门外汉, 所以我一直没有机会去深刻的领会什么是 OOP, 连最基本的类都定义不好. 反倒是学习 F# 后, 经常需要到网络上搜索一些 C# 代码再转换, 这样才能 C# 有了一些了解...

我说我连类都定义不好, 这是个很尴尬的事实. 比如像 C# 的可视化设计器生成的代码那样, 新建一个 Form 修改窗口标题, 再加入一个Button. 这是再简单不过的例子了, 可是用 F# 该如何写呢?

 
// 例子程序里展示了如何使用 FP 的风格建立窗体
let form =
    let form = new Form(Text = "MyForm")
    let b = new Button()
    form.Controls.Add b
    form
// 但是今天我们要讨论的是如何像 C# 那样继承自 Form 实现自己的类
 
// 第一种方法是我在 Simple101 中看到的
// 这是一种被称为详尽语法(Explicit syntax)
// 这是最中规中矩的定义方式 当然也最繁琐
type MyForm1 =
    inherit Form
    val b :Button
    member t.InitializeComponent() =
        t.Text <- "MyForm1"
        t.Controls.Add t.b
    new() as t =
        { b = new Button() }
        then
            t.InitializeComponent()
 
// 第二种是很常规的定义类的方法
// 被称为隐含语法(Implicit syntax)
// 隐含了什么? 我猜是隐含了构造函数吧
// 之前一直疑惑构造函数隐含了 那我怎么调用呢?
type MyForm2() =
    inherit Form()
    let b = new Button()
    member t.InitializeComponent() =
        t.Text <- "MyForm2"
        t.Controls.Add b
 
// 感谢 Tomas Petricek
// 我一直不解的问题终于解开了 原来可以后接 as 语法来指向自己
type MyForm3() as t =
    inherit Form()
    let b = new Button()
    do
        t.Text <- "MyForm3"
        t.Controls.Add b
 
// 感谢 Danny Asher
// 他的方法提醒了我基类的方法是可以直接调用的
type MyForm4() =
    inherit Form()
    let b = new Button()
    do
        base.Text <- "MyForm4"
        base.Controls.Add b
Tags Tags:
Categories: 编程
Posted By: colder
Last Edit: 10 Sep 2008 @ 08 56 上午

E-mailPermalink
 

Responses to this post » (One Total)

 
  1. 思想链接 said...
    10:37 - 九月 9th, 2008

    第一次看到还有这个F#语言,厉害~
    换个链接吧,提携提携~
    我的博客:思想链接
    网址:http://blog.thinkurl.cn/
    你的链接我放好了哦,谢谢了

 

Leave A Comment ...

 

 XHTML:
You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
\/ More Options ...
Change Theme...
  • Role »
  • Posts »
  • Comments »
Change Theme...
  • VoidVoid (Default)
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LiteLightweight
  • No Child Pages...