在C#Generics中需要帮助 [英] Need a Help in C# Generics

查看:68
本文介绍了在C#Generics中需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友,



在编写一个通用函数时需要一些帮助,该函数将获取两种不同类型的输入值并返回另一种不同类型的值。 />


例如public< t>添加< t,u,v>(U obj1,V obj2)其中T:struct

{

}



喜欢发送int和double值并获得string作为输出。或者这些基本类型的任意组合。



请朋友们提供你宝贵的想法。



感谢你

Friends,

Need a small help in writing one generic function that will take input value of two different type and return a value of another different type.

e.g public <t> Add<t,u,v>(U obj1, V obj2) where T:struct
{
}

Like sending a "int" and and "double" value and getting a "string" as output.Or Any combination of these basic types.

Please friends provide your valuable Ideas.

Thanking You

推荐答案

你不能这样做 - 或者不能那些规格。当然你可以在double上添加一个int并在结果上调用ToString(),但如果我将'Exception'作为第三个参数(或其他任何没有意义的东西)传递怎么办?



为了使泛型工作,您需要将通用参数约束到不同可接受类型以相同方式工作的级别。字符串与int或double不兼容。它需要一个特殊情况'ToString()'才能使它工作。你怎么能推断出这种需求对所有类型都是通用的呢?你不能。



也许你最好的选择是抛弃泛型并为你期望的不同类型创建一组重载。
You can't do that - or not to those specifications. Sure you can add an int to a double and call ToString() on the result, but what if I pass an 'Exception' as the third parameter (or anything else which doesn't make sense)?

In order for generics to work, you need to constrain the generic parameters to a level where different acceptable types work the same way. A string is not compatible with int or double. It needs a special case 'ToString()' to make it work. How can you infer this needs doing in a generic manner for all types? You can't.

Perhaps your best bet would be to abandon Generics and just create a set of overloads for the different types you expect.


这篇关于在C#Generics中需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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