开发者

Generic Type Constraint to accept only Numbers? [duplicate]

开发者 https://www.devze.com 2023-03-18 04:42 出处:网络
This question already has answers here: 开发者_开发百科 Closed 11 years ago. Possible Duplicates:
This question already has answers here: 开发者_开发百科 Closed 11 years ago.

Possible Duplicates:

C# generic constraint for only integers

Generics - where T is a number?

In c#:

Imagine a case that we have a functionality over a generic type in which conceptually our generic type is limited only to numbers.

By saying "number" we aim to be able to use multiply, plus, minus, etc. operators on variables of type T.

Unfortunately something like this is not accepted in c#:

public class Image<T> where T : number

Note that performance is also important so we don't want to go for redefining a struct for numeric types and using them.

What do you think is the best way to do this? Or is there any design patter that allows us to have "high performance" arithmetic functions over variables of a generic type?


At the great cost of losing readability, you can rewrite all methods from

int Factorial(int x)
{
    if (x == 0) return 1;
    return x * Factorial(x - 1);
}

to

T Factorial<T>(IReal<T> t, T x)
{
    if (t.Equals(x, t.FromInteger(0))) return t.FromInteger(1);
    return t.Multiply(x, Factorial<T>(t, t.Subtract(x, t.FromInteger(1))));
}

using

interface IEq<T>
{
    bool Equals(T a, T b);
}

interface IOrd<T> : IEq<T>
{
    int Compare(T a, T b);
}

interface IShow<T>
{
    string Show(T a);
}

interface INum<T> : IEq<T>, IShow<T>
{
    T Add(T a, T b);
    T Subtract(T a, T b);
    T Multiply(T a, T b);

    T Negate(T a);

    T Abs(T a);
    T Signum(T a);

    T FromInteger(int x);
}

interface IReal<T> : INum<T>, IOrd<T>
{
}

with implementations for any number type.


Unfortunately there is no such constraint. The closest thing exist is struct constraint

Also you can google math libraries for .net which expose there own types which have one baseclass which makes it possible to use it as a constrain you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号