如何在c#中覆盖或创建括号"[]"的自定义行为?

gSa*_*amp 2 .net c#

可能重复:
如何在C#中重载方括号运算符?

基本上我想知道是否有一种方法来实现类似于SqlDataReader对象的括号的自定义行为.例如,使用SqlDataReader对象,您可以使用索引号"Reader [0]",这是括号的正常操作,或者您可以提供列名"Reader ["id"]".我知道如何覆盖基本运算符,但似乎找不到任何与更改括号行为有关的内容.

Jar*_*Par 14

您需要在类型中定义索引器

public class MyType {
  public string this[int index] {
    get { 
      switch (index) {
        case 1: return "hello";
        case 2: return "world";
        default: return "not found";
      }
    }
    set { ... }
  }
}

MyType t = ...;
Console.WriteLine(t[0]);  // hello
Console.WriteLine(t[1]);  // world
Run Code Online (Sandbox Code Playgroud)