解决方案在.NET泛型重载运算约束 [英] Solution for overloaded operator constraint in .NET generics

查看:114
本文介绍了解决方案在.NET泛型重载运算约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会做什么,如果我想有只接受已重载操作类型,例如减法运算符的通用方法。我试图用一个接口作为约束,但接口不能有运算符重载。

What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading.

什么是实现这一目标的最佳途径?

What is the best way to achieve this?

推荐答案

有没有直接的答案;运营商是静态的,并且不能在约束pssed前$ P $ - 和现有primatives不实现任何特定的接口(对比IComparable的并[d T>],它被用来模拟大于/小于)

There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than).

不过,如果你只是希望它的工作,然后在.NET 3.5有一些选项...

However; if you just want it to work, then in .NET 3.5 there are some options...

我在这里把一个图书馆 ,允许运营商高效和简单的访问泛型 - 如:

I have put together a library here that allows efficient and simple access to operators with generics - such as:

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

可以下载为 MiscUtil

此外,在C#4.0,这通过动态成为可能:

Additionally, in C# 4.0, this becomes possible via dynamic:

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

我也有(在一个点)的.NET 2.0版,但毕竟是少的测试。另一种选择是创建一个接口,如

I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as

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

等等,但你需要传递一个 ICalc&LT;通过了所有的方法T&GT ;; ,它就会变得混乱

这篇关于解决方案在.NET泛型重载运算约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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