Simulate variadic templates in C#

前端 未结 6 940
轮回少年
轮回少年 2020-12-09 14:57

Is there a well-known way for simulating the variadic template feature in C#?

For instance, I\'d like to write a method that takes a lambda with an arbitrary set of p

6条回答
  •  遥遥无期
    2020-12-09 15:47

    I don't necessarily know if there's a name for this pattern, but I arrived at the following formulation for a recursive generic interface that allows an unlimited amount of values to be passed in, with the returned type retaining type information for all passed values.

    public interface ITraversalRoot
    {
        ITraversalSpecification Specify();
    }
    
    public interface ITraverser: ITraversalRoot
    {
        IDerivedTraverser> AndInclude(Expression> path);
    }
    
    public interface IDerivedTraverser : ITraverser
    {
        IDerivedTraverser> FromWhichInclude(Expression> path);
    
        TParentTraverser ThenBackToParent();
    }
    

    There's no casting or "cheating" of the type system involved here: you can keep stacking on more values and the inferred return type keeps storing more and more information. Here is what the usage looks like:

    var spec = Traversal
        .StartFrom()             // ITraverser
        .AndInclude(vm => vm.EnvironmentBrowser) // IDerivedTraverser>
        .AndInclude(vm => vm.Datastore)          // IDerivedTraverser>
        .FromWhichInclude(ds => ds.Browser)      // IDerivedTraverser>>
        .FromWhichInclude(br => br.Mountpoints)  // IDerivedTraverser>>>
        .Specify();                              // ITraversalSpecification
    

    As you can see the type signature becomes basically unreadable near after a few chained calls, but this is fine so long as type inference works and suggests the right type to the user.

    In my example I am dealing with Funcs arguments, but you could presumably adapt this code to deal with arguments of arbitrary type.

提交回复
热议问题