📜  C#|索引器超载

📅  最后修改于: 2021-05-30 00:22:36             🧑  作者: Mango

先决条件:C#中的索引器

像函数一样,索引器也可以重载。在C#中,我们可以在一个类中有多个索引器。要使索引器过载,请使用多个参数声明该索引器,并且每个参数应具有不同的数据类型。索引器通过传递2种不同类型的参数而过载。它与方法重载非常相似。

示例1:在下面的程序中,使用intfloat类型重载索引器。此处,使用int索引器分配了“ Hello ”字,而使用float参数为字符串赋予值“ Geeks ”。

// C# Program to illustrate 
// the overloading of indexers
using System;
  
namespace HelloGeeksApp {
      
class HelloGeeks {
      
    // private array of 
    // strings with size 2
    private string[] word = new string[2];
      
    // this indexer gets executed
    // when Obj[0]gets executed
    public string this[int flag]
    {
          
        // using get accessor
        get
        {
            string temp = word[flag];
            return temp;
        }
          
        // using set accessor
        set
        {
            word[flag] = value;
        }
    }
      
    // this is an Overloaded indexer
    // which will execute when 
    // Obj[1.0f] gets executed
    public string this[float flag]
    {
          
        // using get accessor
        get
        {
            string temp = word[1];
            return temp;
        }
          
        // using set accessor
        set
        {
              
            // it will set value of 
            // the private string 
            // assigned in main
            word[1] = value;
              
        }
    }
      
// Main Method
static void Main(string[] args)
{
    HelloGeeks Obj = new HelloGeeks();
      
    Obj[0] = "Hello"; // Value of word[0]
      
    Obj[1.0f] = " Geeks"; // Value of word[1]
      
    Console.WriteLine(Obj[0] + Obj[1.0f]);
}
}
}
输出:
Hello Geeks

示例2:在下面的程序中,我们仅在启用只读模式的重载索引器中使用get访问器。意味着我们不能修改给定的值。这里, int字符串类型用于重载索引器。公共字符串this [字符串标志]仅包含启用只读模式的get访问器。

// C# program to illustrate the concept
// of indexer overloading by taking 
// only get accessor in overloaded indexer
using System;
  
namespace Geeks {
      
class G4G {
      
    // private array of 
    // strings with size 2
    private string[] str = new string[2];
      
    // this indexer gets called
    // when Obj[0] gets executed
    public string this[int flag]
    {
        // using get accessor
        get
        {
            string temp = str[flag];
            return temp;
        }
          
        // using set accessor
        set
        {
            str[flag] = value;
        }
    }
      
    // this indexer gets called
    // when Obj["GFG"] gets executed
    public string this[string flag]
    {
          
        // using get accessor
        get
        {
            return " C# Indexers Overloading."; // read only mode
        }
    }
      
// Driver Code    
static void Main(string[] args)
{
    G4G Obj = new G4G();
      
    Obj[0] = "This is"; // Value of str[0]
      
    Console.WriteLine(Obj[0] + Obj["GFG"]);
}
}
}
输出:
This is C# Indexers Overloading.

注意:索引器重载不能仅通过更改get块的返回类型来完成。