我试图编写一个扩展方法,将函数HasFactor
添加到C#中的类int
。这种奇妙的作品,像这样:有没有办法编写适用于多种类型的扩展方法?
static class ExtendInt
{
public static bool HasFactor(this int source, int factor)
{
return (source % factor == 0);
}
}
class Program
{
static void Main()
{
int i = 50;
int f = 2;
bool b = i.HasFactor(f);
Console.WriteLine("Is {0} a factor of {1}? {2}",f,i,b);
Console.ReadLine();
}
}
因为Main()
方法变量i
上述声明为int
这个伟大的工程。但是,如果将i
声明为Int16
或Int64
,则扩展方法不会显示,除非将其明确地转换为int
或Int32
。
我现在想申请相同HasFactor
方法Int16
和Int64
。但是,我宁愿不为每种类型的int
编写单独的扩展方法。 I 可能会为Int64
编写单一方法,然后将所有内容明确地转换为Int64
或long
以使扩展方法出现。
理想情况下,我宁愿将相同的扩展方法应用于所有三种类型,而无需复制和粘贴大量代码。
这甚至可能在C#中吗?如果不是,这种情况有没有推荐的最佳做法?
基于Eilon和Marc Gravell的输入,我想我会为'Int64'类型创建一个扩展方法。这应该适用于我正在做的事情。 – 2010-01-02 00:26:18