“奇怪"的 C# 属性语法 [英] “Strange” C# property syntax
问题描述
我刚刚在一个 c# 项目中看到了这个:
I just saw this in a c# project:
public char this[int index]
我认为自己是 C# 的新手;任何人都可以帮助它是什么意思?
I consider myself new to C#; any one can help what it's meaning?
推荐答案
It is an Indexer.
It is an Indexer.
索引器允许类或结构的实例被索引,就像数组.索引器类似于属性,只是它们的访问器采用参数.索引器提供类似数组的语法.它允许访问类型与数组相同的方式.索引器等属性经常访问后备店.我们经常接受一个 int 类型的参数并访问一个数组类型的后备存储.
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters. An indexer provides array-like syntax. It allows a type to be accessed the same way as an array. Properties such as indexers often access a backing store. We often accept a parameter of int type and access a backing store of array type.
从 http://www.dotnetperls.com/indexer
string s = "hello";
Console.WriteLine (s[0]); // 'h'
Console.WriteLine (s[3]); // 'l'
实现索引器
要编写索引器,请定义一个名为 this 的属性,以正方形指定参数括号.例如:
To write an indexer, define a property called this, specifying the arguments in square brackets. For instance:
class Sentence
{
string[] words = "The quick brown fox".Split();
public string this [int wordNum] // indexer
{
get { return words [wordNum]; }
set { words [wordNum] = value; }
}
}
以下是我们如何使用此索引器:
Here’s how we could use this indexer:
Sentence s = new Sentence();
Console.WriteLine (s[3]); // fox
s[3] = "kangaroo";
Console.WriteLine (s[3]); // kangaroo
一个类型可以声明多个索引器,每个索引器都有不同类型的参数.一个indexer 也可以接受多个参数:
A type may declare multiple indexers, each with parameters of different types. An indexer can also take more than one parameter:
public string this [int arg1, string arg2]
{
get { ... } set { ... }
}
索引器在内部编译为名为 get_Item
和 set_Item
的方法,如下所示:
Indexers internally compile to methods called get_Item
and set_Item
, as follows:
public string get_Item (int wordNum) {...}
public void set_Item (int wordNum, string value) {...}
编译器默认选择名称Item
——你实际上可以通过使用以下属性装饰您的索引器:
The compiler chooses the name Item
by default—you can actually change this by
decorating your indexer with the following attribute:
[System.Runtime.CompilerServices.IndexerName ("Blah")]
这篇关于“奇怪"的 C# 属性语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!