• 在命名空间下定义类型


    在命名空间下定义类型

    假设定义的类型要用于其它.NET 语言。应该把它们放在命名空间下,而不是模块中。

    这是由于模块在被编译成 C# 或其它.NET 语言时。被处理成类,在模块中定义的不论什么类型都成为这个类型内部的类。

    尽管对于 C# 来说。这并非什么大问题,可是。假设用命名空间取代模块,C# client代码看起来会更清晰。这是由于在 C# 中,仅仅用using 语句导入(open)命名空间。而假设是在模块中的类型。在 C# 中使用时,就必须把模块名作为前缀。

    让我们看一下这种样例。以下的样例定义了类TheClass,它是在命名空间下;随类一起还提供几个函数,但不能直接放在命名空间下,由于,值不能在命名空间中定义。

    这里,定义了一个名字叫TheModule 模块,来管理函数值。

     

    namespace Strangelights

    open System.Collections.Generic

     

    // this is a counterclass

    type TheClass(i) =

     let mutable theField = i

     member x.TheField

       with get() =theField

     // increments the counter

     member x.Increment() =

       theField <- theField + 1

     // decrements the count

     member x.Decrement() =

       theField <- theField - 1

     

    // this is a module forworking with the TheClass

    module TheModule = begin

     // increments a list of TheClass

     let incList (theClasses: List<TheClass>) =

       theClasses |> Seq.iter (fun c ->c.Increment())

     // decrements a list of TheClass

     let decList (theClasses: List<TheClass>) =

       theClasses |> Seq.iter (fun c ->c.Decrement())

    end

     

    在 C# 中使用TheClass 类,如今就非常简单了,由于不必要加前缀。也能够非常easy地訪问到TheModule 中的相关函数:

     

    // !!! C# Source !!!

    usingSystem;

    usingSystem.Collections.Generic;

    usingStrangelights;

     

    classProgram {

     static voidUseTheClass() {

       // create a list of classes

       List<TheClass> theClasses = newList<TheClass>() {

         new TheClass(5),

         new TheClass(6),

         new TheClass(7)};

     

       // increment the list

       TheModule.incList(theClasses);

     

       // write out each value in the list

       foreach (TheClass c in theClasses) {

         Console.WriteLine(c.TheField);

       }

     }

     static voidMain(string[] args) {

       UseTheClass();

     }

    }

  • 相关阅读:
    Unity3d设置QualitySettings为Beautiful Xcode发布错误
    滚轮拉近相机
    (转)oracle
    (转)Oracle存储过程基本语法
    (转)Oracle执行字符串
    (转)Oracle 临时表用法
    安装包范例
    (转)使用PowerDesigner生成HTML功能
    (转)winform下TCP通信的简单应用
    (转)winform下UPD通信的简单应用
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7010668.html
Copyright © 2020-2023  润新知