简体   繁体   中英

Generic constrain for bitwise operators

So I have a class which looks something like this:

public class Foo<TKey>
{
   ...
}

I have a method which uses the TKey generic as the following:

public int Test(TKey val)
{
   return val | 5;
}

Now I need to set constraints which ensure that TKey is a numeric value in order to use bitwise operators. Anyhow you can not set constraints to ensure that it is a numeric value since short,int,double,... do not implement an interface like INumeric .

Now the question is, would this be possible with only constraints?

Generics are about allowing any Random class that any Programmer on the planet might throw in for T. However the numeric types are actually a very static list. I would never expect a programmer to make his own numeric type. Stuff with a overloaded Operators including binary ones? Maybe rarely.

So this is very much not a generic case. If you only write code for 2 - maybe 3 - types you should cover just about every generic in existence:

  • the highest range integer you have to expect signed Int64 IIRC
  • the highest range floating point you have to expect. IIRC, Decimal*.
  • optionally BigInteger, for when you have to expect really big numbers. However a short look revealed that none ofMath class functions support BigInt values. They keep it to Decimal, Double and many smaler built in Numerics. So this case might have been dropped as to rare and to easy to get wrong.

*Correction: While Decimal has the highest amount of digits of precision and bigest size at 64 bit, Double has the bigger range. By an order of Magnitude, that itself has an order of Magnitude.

Try this code:

    public static int Test<TKey>(TKey val) where TKey : struct, IComparable
    {
        int numberValue = Convert.ToInt32(val);
        return numberValue | 5;
    }

This is should work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM