.NET 数组 | .NET 多项索引 | .NET 多项索引
//在 aardio 中使用 .NET 的 `Item[]` 属性
//.NET 数组: https://www.aardio.com/zh-cn/docs/examples/Languages/dotNet/Array.html
//.NET 多项索引: https://www.aardio.com/zh-cn/docs/examples/Languages/dotNet/Multidimensional-Array.html
import console;
import dotNet;
var compiler = dotNet.createCompiler("C#");
compiler.Source = /******
using System;
using System.Collections.Generic;
namespace CSharpLibrary
{
public class TestClass
{
private Object [] values = new Object [] {1,2,3,4,5,6,7,8,9};
public Object this [int index]
{
get { return values[index]; }
set { values[index] = value; }
}
public Dictionary<string,string> dict = new Dictionary<string,string> ();
}
}
******/
compiler.import("CSharpLibrary"); //编译并引入 C# 命名空间
var netObj = CSharpLibrary.TestClass(); //使用 C# 编写的类构造对象实例
/*
如果使用索引下标操作符 [] 获取成员,
则 aardio 与 C# 一样解析为读取 .NET 对象的 Item[] 属性。
如果 a["b"] 读取值失败且对象 .NET 对象不存在 Item[] 属性,则改为执行 a.b 读取属性。
*/
netObj.dict["test"] = "abc";//写字典的键值
netObj.dict["test2"] = "abc2";//写字典的键值
console.log( netObj.dict["test"] );//读字典的键值
/*
- 无参 Item 可使用 netObj.Item 直接读取。
- 多参数 Item 属性,可以使用添加 get,set 前缀的方法读写。
*/
netObj.setItem(5,123); //写 Item 属性,支持多参数。
var item = netObj.getItem(5); //读 Item 属性,支持多参数。
var item = netObj.Item(5); //get 前缀可以省略,支持多参数。
/*
.NET 起始索引为 0 。
通过对象的下标读取 Item 属性,则起始下标为 1(aardio 1-based 规则)。
*/
var item = netObj[6];//等价于 netObj.Item[6-1]。。
netObj[6] = 123;
/*
极罕见的 C# 对象也有可能自定义起始下标为 1,
如果写 netObj[2] 会很奇怪,可以改为 netObj.Item[1] 。
单参数 Item 应当使用 netObj[index] 替代 netObj.Item[index] 。
如果 netObj.Item 本身就是无参数的属性值则 netObj.Item[index] 存在歧义,
aardio 就不得不执行一次原本不必要地检测(如果 netObj.Item 支持参数则会缓存 Item 包装对象,不会重复检测)。
使用 netObj[index],netObj.Item(index),netObj.getItem(index,...),netObj.setItem(index,...) 都可以避免此问题,
这是因为对 netObj 使用下标操作符或 owner call 调用都可以明确是带参数调用(无歧义)。
*/
/*
.NET 多项索引: https://www.aardio.com/zh-cn/docs/examples/Languages/dotNet/Multidimensional-Array.html
aardio 也支持使用逗号分隔的多项索引访问 .NET 多维数组。
但多项数值索引自 0 开始,aardio 不会自动减 1。
*/
//获取 .NET Dictionary<string,string> 对象
var netDict = netObj.dict;
//通过下标访问字典的键值
var value = netDict["test"]
//遍历 .NET 字典对象
for i,keyValuePair in dotNet.each(netDict) {
console.dump(tostring(keyValuePair))
var key = keyValuePair.Key;
var value = keyValuePair.Value;
console.log("each",key,value)
}
//可用 table.parseValue 将 .NET 对象转换为纯 aardio 表对象
var tab = table.parseValue(netDict)
//.NET 对象默认支持 JSON.stringify 以及基于 JSON.stringify 的 console.dumpJson 等函数
console.dumpJson(netDict)
/*
上面的范例适用所有实现了 .NET 中 IDictionary 接口的 .NET 对象,例如字典(Dictionary)与哈拓表(HashTable)。
*/
console.pause();
Markdown 格式