简体   繁体   English

按位运算符的通用约束

[英]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:我有一个使用TKey泛型的方法,如下所示:

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.现在我需要设置约束以确保TKey是一个数值以便使用按位运算符。 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 .无论如何,您不能设置约束以确保它是一个数值,因为short,int,double,...没有实现像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.泛型是关于允许地球上任何程序员可能为 T 投入的任何 Random 类。然而,数字类型实际上是一个非常静态的列表。 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:如果您只为 2 种(可能是 3 种)类型编写代码,则应该涵盖几乎所有现有的泛型:

  • the highest range integer you have to expect signed Int64 IIRC您必须期望有符号 Int64 IIRC 的最大范围整数
  • the highest range floating point you have to expect.您必须期望的最高范围浮点数。 IIRC, Decimal*. IIRC,十进制*。
  • optionally BigInteger, for when you have to expect really big numbers.可选 BigInteger,用于当您必须期望非常大的数字时。 However a short look revealed that none ofMath class functions support BigInt values.然而,简短的观察显示,没有任何Math 类函数支持 BigInt 值。 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. *更正:Decimal 在 64 位时具有最高的精度和最大的尺寸,而 Double 的范围更大。 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!这是应该工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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