"this"关键字作为属性 [英] The 'this' keyword as a property

查看:52
本文介绍了"this"关键字作为属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常了解C#,但这对我来说很奇怪.在某些旧程序中,我看到了以下代码:

I know C# well, but it is something strange for me. In some old program, I have seen this code:

public MyType this[string name]
{
    ......some code that finally return instance of MyType
}

它怎么称呼?这有什么用?

How is it called? What is the use of this?

推荐答案

它是索引器.声明之后,您可以这样:

It is indexer. After you declared it you can do like this:

class MyClass
{
    Dictionary<string, MyType> collection;
    public MyType this[string name]
    {
        get { return collection[name]; }
        set { collection[name] = value; }
    }
}

// Getting data from indexer.
MyClass myClass = ...
MyType myType = myClass["myKey"];

// Setting data with indexer.
MyType anotherMyType = ...
myClass["myAnotherKey"] = anotherMyType;

这篇关于"this"关键字作为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆