1

I'm trying to model series of "phases" C#, where each phase has an input and output, and where they can be chained together, with the output of phase 1 becoming the input of phase 2. I thought it might look something like this, but I didn't know what to use in place of the ???.

public class Phase<TInput, TOutput>
{
  private Phase<???, TInput> prerequisite;

  public Phase(Phase<???, TInput> prereq, Func<TInput, TOutput> work)
  {
    /* ... */
  }
}

What I'm ultimately trying to do is chain together a series of steps like this (where the "Add" methods are just convenience methods to help me create the phases):

var p1 = AddInitialPhase(() => 
  {
    int a = /* some initial result */;
    return a;
  });

var p2 = AddPhase(p1, (result) =>    
  {
    string b = /* do something with result from p1 */
    return b;
  });

var p3 = AddPhase(p2, (result) =>    
  {
    /* etc... */
  });

Is there any nice type-safe way to do this with generics? Or does anyone have design alternatives I should consider? I can imagine using reflection to do the chaining, or just using objects for the inputs and outputs, but I was hoping there was a better way.

4

1 回答 1

3

你可以尝试两个类:

public class OutputOfPhase<TOutput>
{
}

public class Phase<TInput, TOutput> : OutputOfPhase<TOutput>
{
      private OutputOfPhase<TInput> prerequisite;

      public Phase(OutputOfPhase<TInput> prereq, Func<TInput, TOutput> work)
      {
      /* ... */
      }
}

你这样使用它:

Phase<int, long> p1 = new Phase<int, long>(null, p => p * 1000L);
Phase<long, double> p2 = new Phase<long, double>(p1, p => p / 2.0);

Phase派生自仅包含类的输出部分的基类。您可以将一个类的输出传递给下一个类,而下一个类不需要知道前一个对象的输入。

于 2013-08-03T15:10:52.373 回答