泛型数组中的索引器

本文关键字:索引 数组 泛型 | 更新日期: 2023-09-27 17:56:24

Hi我已经创建了一个通用数组,适用于 Int、String、Float 甚至我自己的名为 Customers 的类型。

泛型数组具有函数Add(),Sort(),ShowAll(),适用于Int,String甚至客户类型。除非我尝试为 CustomerType 显示 All() 方法,该方法显示我通过 ADD() 方法添加的所有值。

输出类似于 GenericArray.Customer

不是我想拥有的值的值.

我已经解决了

public class GArray<T> where T : Customer

但现在我无法创建 Int,浮点型的泛型数组。

这是类的 ADD 和 ShowAll 方法

public void Add(T temp)
        {
            if (index >= values.Length)
            {
                T[] tempArray = new T[values.Length + 1];
                Array.Copy(values, tempArray, values.Length);
                values = tempArray;
            }
            values[index] = temp;
            index++;  
        }
 public void ShowAll()
    {
        for (int i = 0; i < values.Length; i++)
        {
            Console.WriteLine(values[i]);                
        }
    }

值 m 添加

 static void Main(string[] args)
        {                        
            GArray<Customer> customers = new GArray<Customer>(3);
            customers.Add(new Customer(101, "xyz"));
            customers.Add(new Customer(59, "abc"));
            customers.ShowAll();
            }

和我的朋友谈过,他说我必须自己创建索引器。 有人可以帮我如何在这种情况下创建适用于 customerType 或任何类型的索引器。

泛型数组中的索引器

我认为

,如果我理解这个问题(输出类似于 GenericArray.Customer,而不是我想要的值),您应该在客户定义中添加:

public override string ToString()
{
    // return something you want to show to identify your customer
    // e.g. return Name;  
    return ...           
}

我解释:当你使用Console.WriteLine(values[i])时,你告诉 C# 写入控制台客户对象......然后写出类的名称,因为它是默认行为。
在客户类中定义要转换为的默认字符串可以随心所欲...

public T this[int index]
{
  get {return values[index]; }
}

我认为您的问题是您没有在客户类中覆盖ToString。 这样做 - 它将定义对象在控制台中的显示方式。

撇开您的实际问题不谈,我想提一下,数组实现中没有ShowAll方法的位置。为什么数组应绑定到控制台应用程序?难道您不希望有一天在 Windows 窗体应用程序中重用它而无需重写它吗?

接下来,.NET 已经有一个根据需要执行动态分配的List<T>。如果您确实想自己再次编写它,请至少以更大的步骤分配数组(每次 n*2)。

若要从数组中删除 ShowAll 方法(它不属于数组),应考虑采用以下方法之一:

a) 创建一个适用于任何IEnumerable<T>(列表、数组、集合等)的扩展方法:

 public static class EnumExt
{
     public static void ShowAll<T>(this IEnumerable<T> list)
     {
         foreach (T item in list)
            Console.WriteLine(item);
     }
}

用法:

int[] array = new int[] { 1,2,3};
array.ShowAll();

b) 或者,更抽象一点,创建一个ForEach扩展方法,您将在其中传递任意delegate来执行实际工作:

public static class EnumExt
{
     public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
     {
         foreach (T item in list)
            action(item);
     }
}

用法:

int[] array = new int[] { 1,2,3};
// now you are reusing the iterator
// for any action you want to execute
array.ForEach(Console.WriteLine);
// or
array.ForEach(item => Console.WriteLine("My item is: " + item));