需要解释一些代码
本文关键字:代码 解释 | 更新日期: 2023-09-27 18:09:13
public object this[string name]
class ObjectWithProperties
{
Dictionary<string, object> properties = new Dictionary<string, object>();
public object this[string name]
{
get
{
if (properties.ContainsKey(name))
{
return properties[name];
}
return null;
}
set
{
properties[name] = value;
}
}
}
你将能够使用索引(即没有属性名)直接从对象中引用字典中的值
在你的例子中应该是
var foo = new ObjectWithProperties();
foo["bar"] = 1;
foo["kwyjibo"] = "Hello world!"
// And you can retrieve them in the same manner...
var x = foo["bar"]; // returns 1
MSDN指南:http://msdn.microsoft.com/en-gb/library/2549tw02.aspx
基础教程:http://www.tutorialspoint.com/csharp/csharp_indexers.htm
编辑以回答评论中的问题:
这相当于做以下事情:
class ObjectWithProperties
{
public Dictionary<string, object> Properties { get; set; }
public ObjectWithProperties()
{
Properties = new Dictionary<string, object>();
}
}
// instantiate in your other class / app / whatever
var objWithProperties = new ObjectWithProperties();
// set
objWithProperties.Properties["foo"] = "bar";
// get
var myFooObj = objWithProperties.Properties["foo"]; // myFooObj = "bar"