本文介绍了如何使用泛型添加整数和字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的代码中,我想执行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));
}
推荐答案
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();
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.
这篇关于如何使用泛型添加整数和字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!