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

查看:22
本文介绍了'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天全站免登陆