使用c中的索引器在私有数组中对数据进行双列直插

本文关键字:数据 索引 使用 数组 | 更新日期: 2023-09-27 17:58:02

我在索引中声明两个私有数组,并在main中显示数据。然而,它没有显示任何数据。请告诉我如何在索引器中显示两个私有数组中的数据?

class Program
{
    static void Main(string[] args)
    {
        student sc = new student();
        for (int i = 0; i < sc.mlength; i++)
        {
            Console.WriteLine(sc[i]);
        }
        Console.ReadLine();
      //i am declaring two private arrays in indexes and displaying the data in main is not displaying any one tell me how to display the data in the two private arrays in indexers?  
    }
}
public class student
{
    private int[] _marks = new int[] { 60, 68, 70 };
    private string[] _names = new string[] { "suri", "kumar", "suresh" };
    public int this[int i]
    {
        get
        {
            return _marks[i];
        }
        set
        {
            _marks[i] = value;
        }
    }
    public string this[int i]
    {
        get
        {
            return _names[Convert.ToInt32(i)];
        }
        set
        {
            _names[Convert.ToInt32(i)] = value;
        }
    }
    public int mlength
    {
        get
        {
            return _marks.Length;
        }
    }
    public int nlenght
    {
        get
        {
            return _names.Length;
        }
    }
}

}

使用c中的索引器在私有数组中对数据进行双列直插

索引器允许像数组一样使用类。在类内部,您可以按照自己的意愿管理值的集合。这些对象可以是一组有限的类成员、另一个数组或一些复杂的数据结构。不管类的内部实现如何,都可以通过使用索引器一致地获取其数据。下面是一个例子。

示例:

using System;
class IntIndexer
{
private string[] myData;
public IntIndexer(int size)
{
    myData = new string[size];
    for (int i=0; i < size; i++)
    {
        myData[i] = "empty";
    }
}
public string this[int pos]
{
    get
   {
        return myData[pos];
    }
    set
   {
        myData[pos] = value;
    }
}
static void Main(string[] args)
{
    int size = 10;
    IntIndexer myInd = new IntIndexer(size);
    myInd[9] = "Some Value";
    myInd[3] = "Another Value";
    myInd[5] = "Any Value";
    Console.WriteLine("'nIndexer Output'n");
    for (int i=0; i < size; i++)
    {
        Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
    }
}
}

IntIndexer类有一个名为myData的字符串数组。这是一个外部用户看不到的私有数组。此数组在构造函数中初始化,构造函数接受int大小参数,实例化myData数组,然后用单词"empty"填充每个元素。

IntIndexer类有一个名为myData的字符串数组。这是一个外部用户看不到的私有数组。此数组在构造函数中初始化,构造函数接受int大小参数,实例化myData数组,然后用单词"empty"填充每个元素。

下一个类成员是Indexer,它由this关键字和方括号this[int-pos]标识。它接受单个位置参数pos。正如您可能已经猜到的,Indexer的实现与Property相同。它有get和setaccessor,它们的使用方式与Property中的完全相同。此索引器返回一个字符串,如indexer声明中的字符串返回值所示。

Main()方法只是实例化一个新的IntIndexer对象,添加一些值,然后打印结果。这是输出:

Indexer Output
myInd[0]: empty
myInd[1]: empty
myInd[2]: empty
myInd[3]: Another Value
myInd[4]: empty
myInd[5]: Any Value
myInd[6]: empty
myInd[7]: empty
myInd[8]: empty
myInd[9]: Some Value