如何使用泛型创建在C#中添加字符串和Int的通用函数 [英] How Can I Create A Common Function For Adding String And Int In C# Using Generics

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

问题描述

如何使用泛型创建在C#中添加string和int的通用函数。下面的代码我得到一个像操作符+的错误不能用于类型T.当我使用动态我能够得到一个输出。有没有可能的动力学方法?



< private void =eventargs =mode =hold> {

// for srting

string strResult = Add< string>(Hello,Welcome);



// for int

int result = Add< int>(10,15);

}



private T添加< T>(T arg1,T arg2)

{



返回arg1 + arg2;

}

How can i create a common function for adding string and int in C# using generics. Below code i am getting an error like operator + cannot be used with type T. When i used dynamics i am able to get an output. Is there any possible way with out dynamics ?

<private void="" eventargs="" mode="hold"> {
// for srting
string strResult = Add<string>("Hello", "Welcome");

//for int
int result = Add<int>(10, 15);
}

private T Add<T>(T arg1, T arg2)
{

return arg1 + arg2;
}

推荐答案

这没有多大意义。与大多数类和结构一样,您根本无法添加在一起的类型更多。这只对数字和字符串有意义。



由于标准数字加法操作比你的更灵活,所以你所做的事情确实没有优势。尝试做和添加字符串已经完成使用 String.Join [ ^ ]。
This doesn't make a lot of sense. There are far more types that you simply cannot "add" together, like most classes and structures. This only makes sense for numbers and strings.

There really is no advantage to what you're doing as the standard numerical addition operation is more flexible than what you're trying to do and "adding" strings together is already accomplished with String.Join[^].


您不需要任何泛型。 + 运算符已经为 string int 重载:

You do not need any generics for that. The + operator is already overloaded for string and int:
int i = 0;
string str = "";
string result = i + str;
string ret = str + i;



编译; i.ToString()在添加值时在后台调用。


That compiles; i.ToString() is called somewhere in the background when the values are added.


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

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