需要解释一些代码。

时间:2014-06-19 11:25:35

标签: c# c#-4.0

什么是

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;
        }
    }
}

1 个答案:

答案 0 :(得分:6)

您将能够使用索引直接从对象引用词典中的值(即,没有属性名称)

在你的情况下,它将是

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"