通用类型参数转换 [英] Generic type parameter conversion

查看:49
本文介绍了通用类型参数转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我已经使用通用类型委托创建了以下程序,并且具有通用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.


这篇关于通用类型参数转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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