【问题标题】:Need explanation for some code.需要解释一些代码。
【发布时间】:2014-06-19 20:24:58
【问题描述】:

是什么

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

【问题讨论】:

标签: c# c#-4.0


【解决方案1】:

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

在你的情况下

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"

【讨论】:

  • 公共对象 this[string name] 中 this 的意义是什么。
  • 如 MSDN 文档所述,它只是“语法便利”
  • 还有什么办法,代替上面代码中的public object this[string name] :)
  • 扩大了答案,包括一个如何实现这一目标的示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多