zoukankan      html  css  js  c++  java
  • 在命名空间下定义类型

    在命名空间下定义类型

    假设定义的类型要用于其它.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();

     }

    }

  • 相关阅读:
    Centos7配置编译Tenflow1.15 GPU版本笔记
    今年有哪些便宜的国外域名注册商?
    VPS,域名,主机,建站主题,2020黑色星期五优惠大放送
    这些个挂机项目,赚点小钱玩玩
    WPF管理系统开发框架搭建指南,2020从入门到放弃
    智和信通助力荆门电教馆及六所市直学校实现网络智能化运维管理
    智和网管平台政企信创网管监控运维可视化方案
    智和网管平台与统信操作系统完成认证 强力支撑信创国产替代进程
    GIT基础操作与理解
    高数复习一(数列极限)
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7010668.html
Copyright © 2011-2022 走看看