gpt4 book ai didi

c# - C# 中的 Luatable 等价物?

转载 作者:太空宇宙 更新时间:2023-11-03 10:26:07 24 4
gpt4 key购买 nike

我一直在寻找一种在 C# (3.5) 中制作类似表格的方法,但仍然是空的。基本上我想这样做

    var myClassVar = new myClass();
myClassVar["hello"]["world"] = "hello world";
myClassVar["hello"][0] = "swapped";
myClassVar[0][0] = "test";
myClassVar["hello"]["to"]["the"]["world"] = "again";
myClassVar[0][1][0][0] = "same as above sorta";

我正在尝试创建这种类型的类来解析我为存储数据而创建的文件格式。有人知道这样的事情吗?

最佳答案

public class LuaTable
{
private Dictionary<object, dynamic> properties = new Dictionary<object, dynamic>();
public dynamic this[object property]
{
get
{
if (properties.ContainsKey(property))
return properties[property];
LuaTable table = new LuaTable();
properties.Add(property, table);
return table;
}
set
{
if (!properties.ContainsKey(property))
properties.Add(property, value);
else
properties[property] = value;
}
}
}

您可以完全按照自己的意愿使用它:

var myClassVar = new LuaTable();
myClassVar["hello"]["world"] = "hello world";
myClassVar["hello"][0] = "swapped";
myClassVar[0][0] = "test";
myClassVar["hello"]["to"]["the"]["world"] = "again";
myClassVar[0][1][0][0] = "same as above sorta";

string s1 = myClassVar["hello"]["world"]; // = "hello world"
string s2 = myClassVar["hello"][0]; // = "swapped"
string s3 = myClassVar[0][0]; // = "test"
string s4 = myClassVar["hello"]["to"]["the"]["world"]; // = "again"
string s5 = myClassVar[0][1][0][0]; // = "same as above sorta"

编辑:我刚刚意识到 C# 3.5 没有dynamic,所以这是一个只使用泛型的版本。我希望这没问题(因为您确实必须让表的所有子属性都属于同一类型(在本例中为 string):

public class LuaTable<T> where T : class
{
private bool isValue;
private T value = null;
private Dictionary<object, LuaTable<T>> properties = new Dictionary<object, LuaTable<T>>();

public static implicit operator LuaTable<T>(T val)
{
if (val is LuaTable<T>)
return (LuaTable<T>)val;
return new LuaTable<T>() { isValue = true, value = val };
}
public static implicit operator T(LuaTable<T> table)
{
if (table.isValue)
return table.value;
return table;
}

public LuaTable<T> this[object property]
{
get
{
if (isValue)
return null;

if (properties.ContainsKey(property))
return properties[property];
LuaTable<T> table = new LuaTable<T>();
properties.Add(property, table);
return table;
}
set
{
if (!properties.ContainsKey(property))
properties.Add(property, value);
else
properties[property] = value;
}
}
}

使用起来,和上面的几乎一模一样。只需更改第一行:

var myClassVar = new LuaTable<string>();

关于c# - C# 中的 Luatable 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31567999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com