“聊斋志异”C#属性语法 [英] “Strange” C# property syntax

查看:102
本文介绍了“聊斋志异”C#属性语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚看到这个在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?

推荐答案

有一个索引。

索引器允许类或结构的实例进行索引,就像
  阵列。索引器性能相似,只是他们需要访问
  参数。
  一个索引提供类似数组的语法。它允许进行访问的类型
  方式相同的阵列。如索引属性常常访问
  后备存储。我们经常接受整型和访问的参数
  数组类型的后备存储。

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'

实施一个索引

要编写一个索引,定义一个名为此属性,指定方的论点
括号。例如:

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

一个类型可以声明多个索引,每个不同类型的参数。一个
索引也可以采取多个参数:

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 ,如下:

public string get_Item (int wordNum) {...}
public void set_Item (int wordNum, string value) {...}

编译器选择的名称项目在默认情况下,你实际上可以改变这个
具有以下属性装饰你的索引:

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屋!

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