如果我想要一个只接受重载运算符的类型的泛型方法,例如减法运算符,我该怎么办?我尝试使用接口作为约束,但接口不能有运算符重载。

实现这一目标的最佳方法是什么?

有帮助吗?

解决方案

没有立即回答;运算符是静态的,不能用约束表示 - 并且现有的原型不会实现任何特定的接口(与IComparable [<!> lt; T <!> gt;]形成对比,可以用来模拟大于/小于-than)。

然而;如果你只是想让它工作,那么在.NET 3.5中有一些选项......

我已将此处的图书馆整合在一起通过泛型简单访问运算符 - 例如:

T result = Operator.Add(first, second); // implicit <T>; here

可以将其下载为 MiscUtil 的一部分

此外,在C#4.0中,这可以通过dynamic

实现
static T Add<T>(T x, T y) {
    dynamic dx = x, dy = y;
    return dx + dy;
}

我也曾(曾经)拥有一个.NET 2.0版本,但测试的次数较少。另一种选择是创建一个接口,如

interface ICalc<T>
{
    T Add(T,T)() 
    T Subtract(T,T)()
} 

等等,但是你需要传递一个ICalc<T>;所有方法,这会弄得一团糟。

其他提示

我发现IL实际上可以很好地处理这个问题。防爆。

ldarg.0
ldarg.1
add
ret

在通用方法中编译,只要指定了基本类型,代码就可以正常运行。可以将其扩展为在非基本类型上调用操作符函数。

请参阅此处

有一段代码从内部被盗,我为此使用了很多。它使用IL基本算术运算符查找或构建。这一切都在Operation<T>泛型类中完成,您所要做的就是将所需的操作分配给委托。喜欢add = Operation<double>.Add

它的用法如下:

public struct MyPoint
{
    public readonly double x, y;
    public MyPoint(double x, double y) { this.x=x; this.y=y; }
    // User types must have defined operators
    public static MyPoint operator+(MyPoint a, MyPoint b)
    {
        return new MyPoint(a.x+b.x, a.y+b.y);
    }
}
class Program
{
    // Sample generic method using Operation<T>
    public static T DoubleIt<T>(T a)
    {
        Func<T, T, T> add=Operation<T>.Add;
        return add(a, a);
    }

    // Example of using generic math
    static void Main(string[] args)
    {
        var x=DoubleIt(1);              //add integers, x=2
        var y=DoubleIt(Math.PI);        //add doubles, y=6.2831853071795862
        MyPoint P=new MyPoint(x, y);
        var Q=DoubleIt(P);              //add user types, Q=(4.0,12.566370614359172)

        var s=DoubleIt("ABC");          //concatenate strings, s="ABCABC"
    }
}

<=>源代码由paste bin提供: http://pastebin.com/nuqdeY8z

以下归因:

/* Copyright (C) 2007  The Trustees of Indiana University
 *
 * Use, modification and distribution is subject to the Boost Software
 * License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *  
 * Authors: Douglas Gregor
 *          Andrew Lumsdaine
 *          
 * Url:     http://www.osl.iu.edu/research/mpi.net/svn/
 *
 * This file provides the "Operations" class, which contains common
 * reduction operations such as addition and multiplication for any
 * type.
 *
 * This code was heavily influenced by Keith Farmer's
 *   Operator Overloading with Generics
 * at http://www.codeproject.com/csharp/genericoperators.asp
 *
 * All MPI related code removed by ja72. 
 */
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top