我一直在寻找一种方法来在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";
我正在尝试创建这种类来解析我为存储数据而创建的文件格式。有谁知道这样的事情?
答案 0 :(得分:2)
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>();