C#泛型用于某些类型的数字,其中约束不起作用

时间:2012-01-25 21:42:39

标签: c# generics types casting

我使用泛型很多但是狭隘的案例挑战我......

   public static T RandomNumberImproved <T>(int min, int max)
   {
       bool bolLegit=false;
       if (typeof(T) == typeof(int))
       {
           bolLegit=true;
           return (T) RandomNumberLong(min, max);
       }

       if (typeof(T) == typeof(double))
       {
           bolLegit=true;
           return (T) RandomNumberDouble(min, max);
       }
  if(!bolLegit) throw new Exception("Unsupported Number Format");

   }// end RandomNumberImproved

当然我得到的错误无法转换为返回类型T.

当我可以支持n种类型和时,很多我的通用代码都很有用 当约束有帮助时。像这样的案件让我感到困扰....

1 个答案:

答案 0 :(得分:1)

这不是仿制药的用途。

我建议您将此方法拆分为两种方法RandomNumberInt32和RandomNumberDouble。

然而,有一种方法可以使这项工作:

return (T)(object)RandomNumberLong(min, max);

但它有令人讨厌的表现并且反直觉。我非常喜欢专门的方法替代。

我不明白为什么这个问题被低估了。