我能否使用泛型创建一个采用整数类型的方法,并且仍然能够在该方法内对这些类型执行基本的数学运算?
我的情况:我写了一个方法,它接受一个 int 类型的值,并返回该值是否为质数。后来我需要该方法来处理更大的数字,所以我将输入类型更改为 Int64,但这对速度有负面影响。效率在这里非常重要。
我对泛型知之甚少,但认为它会阻止我拥有两个几乎相同的重载方法。但是我无法让它工作,我不知道是不是因为我试图错误地使用泛型,或者我是否有语法错误。
我认为将类型限制为“int”和“UInt64”将允许我在方法内部使用数学运算符,例如“>”和“%”,但这似乎不起作用。
引用代码:
/// <summary>
/// Tests whether a number is prime.
/// </summary>
public static bool IsPrime<T>(T numToTest) where T: int, UInt64
{
List<T> primeList = new List<T>();
primeList.Add(2); // Give the list an initial prime number. error here when using generics.
return IsPrime(numToTest, primeList);
}
/// <summary>
/// Tests whether a number is prime. Takes an initial list of primes as input to speed the method up.
/// </summary>
public static bool IsPrime<T>(T numToTest, List<T> primeList)
{
bool isPrime = true;
T limit = (T)Math.Sqrt(numToTest); //error here when using generics.
primeList = Prime.AllPrimesUnder(limit, primeList); // If we don't have enough primes to properly test the number, get more.
foreach (T prime in primeList)
{
if (prime > limit) //error here when using generics.
break;
if (numToTest % prime == 0) //error here when using generics.
{
isPrime = false;
break;
}
}
return isPrime;
}
我所知道的唯一选择是:
public static bool IsPrime<int>(int numToTest, List<int> primeList)
public static bool IsPrime<UInt64>(UInt64 numToTest, List<UInt64> primeList)
public static bool IsPrime<BigInteger>(BigInteger numToTest, List<BigInteger> primeList)
等等等等......
请您参考如下方法:
您可以在 .NET 4.0 中使用 dynamic 关键字
public static T Add<T>(T x, T y)
{
return (T)((dynamic)x+(dynamic)y);
}
static void Main(string[] args)
{
int a=Add(10, 11);
long b=Add(34L, 23L);
uint c=Add(4u, 15u);
}
甚至自定义类型
public struct MyInt
{
public static MyInt operator+(MyInt a, MyInt b)
{
}
}
{
MyInt d=new MyInt(...);
MyInt e=new MyInt(...);
MyInt f=Add(d, e);
}
