c# - 如何在我自己的通用方法中使用 Math.Abs​​?

标签 c#

<分区>

以下代码无法编译

... cannot convert T to int bla bla bla

bool IsEqual<T>(this T a, T b, T offset)
{
    a = Math.Abs(a);
    b = Math.Abs(b);
    if (Math.Abs(a - b) < offset)
        return true;
    else
        return false;
}

如何在我自己的泛型方法中使用 Math.Abs​​

最佳答案

如果 .Net 有接口(interface),比如 Java 中的Number,你完全可以放一些东西喜欢

 // Doesn't compile; just the idea
 bool IsEqual<T>(this T a, T b, T offset) 
   where T: Number { // <- T can be any integer or floating point type 
     a = Math.Abs(a);
     ....

不幸的是,.Net 不提供这样的接口(interface),因此您必须实现 IsEqual重载版本:

  bool IsEqual(this Double a, Double b, Double offset) {
    return (Math.Abs(a - b) < offset);
  }

  bool IsEqual(this Single a, Single b, Single offset) {
    return (Math.Abs(a - b) < offset); 
  }

  bool IsEqual(this long a, long b, long offset) {
    return (Math.Abs(a - b) < offset);
  }

  bool IsEqual(this int a, int b, int offset) {
    return (Math.Abs(a - b) < offset);
  }
  ...

关于c# - 如何在我自己的通用方法中使用 Math.Abs​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22088716/

相关文章:

c# - 如何通过实体键添加/删除与 Entity Framework 的多对多关系?

c# - 如何在方法内部更改变量并在外部更改它

c# - 在 DataGridView 中查找字符串

c# - 通过通用接口(interface)/抽象类实现使 .NET Core DI 自动解析类

c# - 使用带有 c dll 的后台工作程序

c# - 将文本拆分为最大长度的行

c# - 从数据库中选择数据,使用今天的日期作为标准

c# - 要集成到 .NET 堆栈中的搜索引擎

c# - Asp.net Webapi 使用 [FromUri] 和具有两个参数的路由

c# - DocumentCollection.Open() 函数不工作 AutoCAD API