创建通用基础

时间:2012-02-23 01:08:38

标签: c# c#-4.0 refactoring

我正在尝试将我的genric功能拉到基类,但是不同的数据类型阻止我这样做。请参阅:

public class OutWriter
{
    private readonly IEnumerable<long> series1;
        private readonly IEnumerable<long> series2
        private readonly IEnumerable<long> series3
        private readonly IEnumerable<double> series4
        private readonly double sum;

public OutWriter()
{
  series1 = PopulateS1()
  series2 = PopulateS2()
  series3 = PopulateS3()
  series4 = PopulateS4()

sum = series4.Aggregate((x,y)=>x+y);
}
}

public class PaperWriter
{
    private readonly IEnumerable<BigInteger> series1;
        private readonly IEnumerable<BigInteger> series2
        private readonly IEnumerable<BigInteger> series3
        private readonly IEnumerable<BigInteger> series4
        private readonly BigInteger sum;

public PaperWriter()
{
  series1 = PopulateS1()
  series2 = PopulateS2()
  series3 = PopulateS3()
  series4 = PopulateS4()

sum = series4.Aggregate((x,y)=>x+y);
}
}

public class Base<T>()
{
    ????
}

我正试图提升相似之处,但涉及longdoubleBigInteger。此外,由于+操作,聚合会抛出编译时错误。你能告诉我怎么做得恰到好处吗?

谢谢, -Mike

1 个答案:

答案 0 :(得分:1)

C#中没有任何东西可以统一数学环。有一些解决方法,例如臭名昭​​着的Jon Skeet维护的MiscUtil包,以及另一个StackOverflow freqenter Marc Gravel编写的Operator实用程序,可以找到它的使用说明here。这个想法是将加法,乘法等操作作为函数调用提取出来。该链接提供了一个Operator类,它使用表达式来提供加法,乘法,除法,减法,小于等式和其他运算符......而且它们都很容易扩展。