在命名空间下定义类型
在命名空间下定义类型
假设定义的类型要用于其它.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();
}
}
相关文章
- ASP.NET找不到类型或命名空间名称怎么办
- 使用泛型存储不同类型的数据
- Go语言中的注释类型和代码风格
- Python3 解释执行字符串类型的代码
- 动态隐藏某些特殊类型的SAP CRM附件
- SAP Spartacus的三种页面类型和对应的路由参数
- WCF调试异常信息:找不到类型“”,在 ServiceHost 指令中提供为 Service 特性值,或在配置元素 system.serviceModel/serviceHosting
- 命名空间“HaiChuang.AMAC”中不存在类型或命名空间名称“WCFClient”。是否缺少程序集引用?
- 【MATLAB】变量 ( 变量引入 | 变量类型 )
- WPF System.InvalidCastException: 无法将类型为“System.Windows.Media.Color”的对象强制转换为类型“System.Windows.Media.Brush”。
- c++枚举类型(二) 命名空间
- 2019年Android恶意软件专题报告:未来移动安全呈现四大趋势——资费消耗与隐私窃取分别以高达46.8%和41.9%的占比,成为横行无忌的主要恶意软件类型,其次分别为远程控制、流氓行为、恶意扣费和欺诈软件。
- C++基础知识要点--变量和基本类型 (Primer C++ 第五版阅读笔记)
- Matlab/Simulink Coder: 代码生成中的数据处理类型控制