如何使用泛型添加整数和字符串数组 [英] How do I add integer and string array by using generics

查看:111
本文介绍了如何使用泛型添加整数和字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我想执行int数组的泛型添加以及字符串数组的添加。

所以如何通过使用泛型实现这一点。

In the below code I want to perform the generics add of int array as well as add of string array.
so how to achieve this by using generics.

class Program
    {
        static void Main(string[] args)
        {
            int[] x = new int[] { 10, 20, 30, 40 };
            string[] y = new string[] { "Himanshu", "Panjabi" };
            ArrayCalc<int> ac1 = new ArrayCalc<int>();
            int r1 = ac1.Add(x);

            Console.WriteLine(r1);
            //ArrayCalc<string> ac2=new ArrayCalc<string>();
            //string r2=ac2.Add(y);

            //int[] a = new int[] { 2, 4, 6, 8, 10 };
            //int res = a.Sum();
            //Console.WriteLine(res);
            Console.ReadLine();
        }
    }
    public class ArrayCalc<T> where T : IComparable
    {
        public T Add(T[] t1)
        {
            T t3 = default(T);
            if (t1 is int[])
            {
                int[] num = new int[10];
                int res = Convert.ToInt32(num.Sum());
                //int asum=num.Sum();
                //int num1 =Convert.ToInt32(t1);
                // int num2 = Convert.ToInt32(t2);
                //int res = num1;
                T files = (T)System.Convert.ChangeType(res, typeof(T));
                return files;
            }
            //else if (t1 is string)
            //{
            //    return (T)System.Convert.ChangeType(x, typeof(T));
            //}
            else
                return (T)System.Convert.ChangeType(t3, typeof(T));


        }

推荐答案

试试这个





Try this


public T Add(T[] t1)
       {
           T t3 = default(T);
           if (t1 is int[])
           {
               int[] temp = t1 as int[];
               int[] num = new int[10];
               var res = temp.Sum();


首先,我必须告诉您对ArrayCalc类的想法不适用于泛型类。泛型的主要好处是可以为各种类型使用完全相同的代码。如果您必须在不同类型的代码中进行区分,以使其工作,那么这种好处就会丢失。在这些情况下,按类型单独实现逻辑会更有意义。



但是,只是为了向您展示如何实现您的课程,这是我的看法:

First, I must tell you that your idea of that ArrayCalc-class isn't a good use for a generic class. The main benefit of generics is that you can use exactly the same code for various types. If you have to make a case-distinction in your code between different types to make it work, that benefit is lost. In those cases it makes much more sense to implement the logic separately per type.

However, just to show you how your class could be implemented, here's my take:
using System;
using System.Linq;
					
public class Program
{
    public static void Main()
    {
        int[] integers = new int[] { 10, 20, 30, 40 };
        string[] strings = new string[] { "Himanshu", "Panjabi" };

        ArrayCalc<int> calcInt = new ArrayCalc<int>();
        int sum = calcInt.Add(integers);
        Console.WriteLine(sum);

        ArrayCalc<string> calcString = new ArrayCalc<string>();
        string joined = calcString.Add(strings);
        Console.WriteLine(joined);
    }

    public class ArrayCalc<T>
    {
        public T Add(T[] array)
        {
            if (array is int[])
            {
                int[] numbers = array as int[];
                int sum = numbers.Sum();
                return (T)(object)sum;       // <-- UGLY!
            }
            else if (array is string[])
            {
                string[] strings = array as string[];
                string joined = String.Join("", strings);
                return (T)(object)joined;    // <-- UGLY!
            }
            else
                throw new NotSupportedException("can't add " + typeof(T).Name);
        }
    }
}



控制台输出:


Console-output:

100
HimanshuPanjabi





正如UGLY!所示,这种错误使用(说实话)你的泛型基于泛型类型进行大小写区分也会导致对泛型类型 T 进行必要的丑陋反向转换,以便能够在没有编译器抱怨的情况下返回结果。



As indicated by "UGLY!", this mis-use (to be honest) of generics where you make case-distinctions based on the generic type also leads to neccessary ugly reverse-casts to the generic type T in order to be able to return the result without the compiler complaining about it.


ArrayList不支持泛型,因此您无法为类型创建任何类型的 ArrayList int string



使用列出< t> 代替。



例如列表与LT; INT> coll = new List< int>();



这是两者之间的差异 - http://www.aspsnippets.com/Articles/Difference-between- ArrayList-and-Generic-in-C-Net-and-VBNet.aspx [ ^ ]。
An ArrayList does not support generics so you cannot create any ArrayList of a type for e.g. int or string.

Use List<t> instead.

For e.g. List<int> coll = new List<int>();

Here is a difference between both of them - http://www.aspsnippets.com/Articles/Difference-between-ArrayList-and-Generic-List-in-C-Net-and-VBNet.aspx[^].


这篇关于如何使用泛型添加整数和字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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