通用类型参数转换

编程入门 行业动态 更新时间:2024-10-20 07:37:10
本文介绍了通用类型参数转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经使用通用类型委托创建了以下程序,并且具有通用Tresult的返回类型.但是由于类型转换错误,Calculator.division方法将无法运行. 请给我建议解决方案 在此先感谢.

Hi, i have create following programm with generic type delegate and has a return type of generic Tresult.but Calculator.division method won''t run due to type conversion error. plz suggest me solution thanks in advance.

public delegate Tresult MyDelegate<T, F, Tresult>(T number1, F number2); class Program { static void Main(string[] args) { MyDelegate<int, int, double> mydel = new MyDelegate<int, int, double>(new Calculator<int, int, double>().division); double a= mydel(5,7); Console.WriteLine(a); Console.ReadKey(); } } public class Calculator<T, F, Tresult> { public Tresult division(T t, F f1) { if(typeof(Tresult)==typeof(double)) return Convert.ToDouble(t) * Convert.ToDouble(f1) as Tresult; } }

[edit]移动了代码块,转义了HTML的代码,整理了较小的布局-OriginalGriff [/edit]

[edit]Code block moved, escaped HTML reverted, minor layout tidy up - OriginalGriff[/edit]

推荐答案

Y.但这不是你的错,这很糟糕. Yuck. But not strictly your fault it''s yuck. return Convert.ToDouble(t) * Convert.ToDouble(f1) as Tresult;

您不能使用as Tresult,因为Tresult可以是任何类型,并且它不知道是否存在转换.您可以限制Tresult的类型以使其与T和/或F兼容,但这也很麻烦.

You can''t use as Tresult because Tresult could be any type, and it doesn''t know if there is a conversion. You could constrain the types of Tresult to be compatible with T and / or F, but that also is a messy job.

return (Tresult) (Convert.ToDouble(t) * Convert.ToDouble(f1));

您不能进行强制转换,因为它会尝试从未指定的类型中查找直接转换.讨厌.

You can''t cast it because it tries to find a direct conversion from an unspecified type. Nasty.

return (Tresult) (object) (Convert.ToDouble(t) * Convert.ToDouble(f1));

您可以通过对对象进行两次强制转换来编译它(因为任何内容都可以强制转换为对象,并且一切都源自对象). 在实践中会可靠地工作吗?可能不是.最好的猜测是运行时异常,因为缺少转换.如果您真的很小心使用什么类型,它可能会起作用,但是... 我将避免使用这样灵活的泛型方法,仅是因为它们是可以完全测试的真正的PITA.

You can get it to compile by doing a double cast via object (since anything can be cast to an object, and everything is derived from object). Will it work reliably in practice? Probably not. Best guess is run time exceptions because of the lack of conversions. It may work if you are really careful what types you use, but... I would avoid having such flexible generic methods, if only because they are a real PITA to test fully.

更多推荐

通用类型参数转换

本文发布于:2023-11-11 23:19:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579819.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!