5

これは私が達成しようとしているものです:

config.Name("Foo")
      .Elements(() => {
                         Element.Name("element1").Height(23);
                         Element.Name("element2").Height(31);
                      })
     .Foo(23);

またはこのように:

  .Elements(e => {
                     e.Name("element1").Height(23);
                     e.Name("element2").Height(31);
                  })
  .Foo(3232);

これは私が今のところ持っているものです:

public class Config
{
   private string name;
   private int foo;
   private IList<Element> elements = new List<Element>();

   public Config Name(string name)
   {
      this.name = name;
      return this;
   }

   public Config Foo(int x)
   {
       this.foo = x;
   }

   ... //add method for adding elements 

   class Element
   {
      public string Name { get; set; }
      public int Height { get; set; }
   }
}

誰もこれを行う方法を知っていますか?

4

6 に答える 6

5
public class Config
{
   private string name;
   private IList<Element> elements = new List<Element>();
   public IList<Element> GetElements {get {return this.elements;}}
   public Config Name(string name)
   {
      this.name = name;
      return this;
   }

   public Config Elements(IEnumerable<Element> list)
   {
        foreach ( var element in list)
            elements.Add(element);
        return this;
   }

   public Config Elements(params Element[] list)
   {
        foreach ( var element in list)
            elements.Add(element);
        return this;
   }

   public Config Elements(params Expression<Func<Element>>[] funcs)
   {
        foreach (var func in funcs )
            elements.Add(func.Compile()());
        return this;
   }

   public Config Elements(params Expression<Func<IEnumerable<Element>>>[] funcs)
   {
        foreach (var func in funcs )
            foreach ( var element in func.Compile()())
                elements.Add(element);
        return this;
   }

   public class Element
   {
      public string Name { get; set; }
      public int Height { get; set; }     
      public Element() {}
      public Element(string name)
      {
         this.Name = name;
      }  
      public Element AddHeight(int height)
      {
          this.Height = height;
          return this;
      }
      public static Element AddName(string name)
      {
        return new Element(name);
      }
   }
}

利用方法

var cfg = new Config()
    .Name("X")
    .Elements(new [] { new Config.Element { Name = "", Height = 0} })
    .Elements(
            Config.Element.AddName("1").AddHeight(1), 
            Config.Element.AddName("2").AddHeight(2) 
            )
    .Elements(
        () => Config.Element.AddName("1").AddHeight(1)
    )
    .Elements(
        () => new[] {
                Config.Element.AddName("1").AddHeight(1),
                Config.Element.AddName("1").AddHeight(1)
               }
    )
于 2012-04-27T09:02:05.620 に答える
3

私はむしろ次の流暢なインターフェースを使いたいです:

Config config = new Config("Foo")
                        .WithElement("element1", 23)
                        .WithElement("element2");

読みやすくコンパクトだと思います。実装:

public class Config
{
    private string name;
    private IList<Element> elements = new List<Element>();

    public Config(string name)
    {
        this.name = name;
    }

    public Config WithElement(string name, int height = 0)
    {
        elements.Add(new Element() { Name = name, Height = height });
        return this;
    }

    class Element
    {
        public string Name { get; set; }
        public int Height { get; set; }
    }
}

nameがオプションの場合は、パラメーターなしでConfigコンストラクターを追加します。高さと名前の両方が必要ない場合は、WithElemntメソッドのオプションのパラメーターも検討してください。

更新:名前のみを指定して要素を追加する方法を示すために、heightをオプションのパラメーターに変更しました。

UPDATE(要素のグループを1つだけ許可する場合)

Config config = new List<Element>()
                    .AddElement(new Element {Name = "element1", Height = 23 })
                    .AddElement(new Element {Name = "element2" })
                    .WrapToConfig()
                    .Name("config1");

実装:

public static class ConfigurationHelper
{
    public static IList<Element> AddElement(this IList<Element> elements, Element element)
    {
        elements.Add(element);
        return elements;
    }

    public static Config WrapToConfig(this IList<Element> elements)
    {
        return Config(elements);
    }
}

しかし、これはユーザーにとってあまり明白ではないので、最初のシンプルで流暢なインターフェースを使用します。

于 2012-04-27T09:43:42.863 に答える
2

オブジェクトとコレクションの初期化子を使用したくない理由はありますか?

public class Config
{
   public string Name { get; set; }
   public int Foo { get; set; }
   public IList<Element> Elements { get; private set; }

   public Config()
   {
       Elements = new List<Element>();
   }
}

// I'm assuming an element *always* needs a name and a height
class Element
{
   public string Name { get; private set; }
   public int Height { get; private set; }

   public Element(string name, int height)
   {
       this.Name = name;
       this.Height = height;
   }
}

それで:

var config = new Config
{
    Name = "Foo",
    Elements = { 
        new Element("element1", 23),
        new Element("element2", 31)
    },
    Foo = 23
};

要素のリストを直接公開したくない場合は、いつでもそれをビルダーに変換し、よりプライベートなデータ構造にコピーできますBuild

var config = new Config.Builder
{
    Name = "Foo",
    Elements = { 
        new Element("element1", 23),
        new Element("element2", 31)
    },
    Foo = 23
}.Build();

Configこれには、それ自体を不変にできるという追加の利点があります。

常に存在する必要Nameがある場合は、代わりにそれをコンストラクターパラメーターとして使用してください。

変更 (またはコピーと変更) メソッド呼び出しを備えた流暢なインターフェイスを使用するのが良い場合もありますが、この場合、コレクション/オブジェクト初期化子はより慣用的な C# だと思います。

C# 4 を使用していて、Elementコンストラクターを呼び出したい場合は、いつでも名前付き引数を使用できることに注意してください。

new Element(name: "element2", height: 31)
于 2012-05-01T06:22:09.513 に答える
1

データ ビルダー パターンを使用します。これの良いところは、流暢なビルド API をデータ オブジェクトから分離していることです。もちろん、規則では "with" を省略できます。

使用法:

var aConfig = new ConfigBuilder();

// create config fluently with lambdas
Config config = aConfig.WithName("Foo")
        .WithElement(e => e.WithName("element1").WithHeight(23))
        .WithElement(e => e.WithName("element2").WithHeight(31))
    .WithFoo(3232)
    .Build();

// create elements in one go
config = aConfig.WithName("Foo")
         .WithElements(
             e => e.WithName("element1").WithHeight(23), 
             e => e.WithName("element2").WithHeight(31))
     .WithFoo(3232)
     .Build();


var anElement = new ElementBuilder();

// or with builders 
config = aConfig.WithName("Foo")
        .WithElement(anElement.WithName("element1").WithHeight(23))
        .WithElement(anElement.WithName("element2").WithHeight(31))
    .WithFoo(3232)
    .Build();

// use builders to reuse configuration code
anElement.WithHeigh(100);

config = aConfig.WithName("Bar")
        .WithElement(anElement.WithName("sameheight1"))
        .WithElement(anElement.WithName("sameheight2"))
    .WithFoo(5544)
    .Build();

実装:

public class ConfigBuilder
{
    private string name;
    private int foo;
    private List<Element> elements = new List<Element>();

    public ConfigBuilder WithName(string name)
    {
         this.name = name;
         return this;
    }

    public ConfigBuilder WithFoo(int foo)
    {
        this.foo = foo;
        return this;
    }

    public ConfigBuilder WithElement(Element element)
    {
        elements.Add(element);
        return this;
    }

    public ConfigBuilder WithElement(ElementBuilder element)
    {
        return WithElement(element.Build());
    }

    public ConfigBuilder WithElement(Action<ElementBuilder> builderConfig)
    {
         var elementBuilder = new ElementBuilder();
         builderConfig(elementBuilder);
         return this.WithElement(elementBuilder);
    }

    public ConfigBuilder WithElements(params Action<ElementBuilder>[] builderConfigs)
    {
         foreach(var config in builderConfigs)
         {
              this.WithElement(config);
         }

         return this;
    }

    public Config Build()
    {
         return new Config() 
         { 
             Name = this.name,
             Foo = this.foo,
             Elements = this.elements
         };
    }
}

public class ElementBuilder
{
    private string name;
    private int height;

    public ElementBuilder WithName(string name)
    {
        this.name = name;
        return this;
    }

    public ElementBuilder WithHeight(int height)
    {
        this.height = height;
        return this;
    }

    public Element Build()
    {
        return new Element() 
        { 
            Name = this.name,
            Height = this.height
        };
    }
}

public class Config
{
    public string Name { get; set; }
    public int Foo { get; set; }
    public IList<Element> Elements { get; set; }
}

public class Element
{
    public string Name { get; set; }
    public int Height { get; set; }
}
于 2012-04-30T14:06:26.173 に答える
1

Here's method 1 to place inside Config -- "one at a time":

public Config Element(Action<Element> a) {
    Element e = new Element();
    a(e);
    this.elements.Add(e);
    return this;
}

And here's how to use it:

config.Name("Foo")
    .Element(e => e.Name("element1").Height(23))
    .Element(e => e.Name("element2").Height(31))
    .Foo(3232);

Here's method 2 -- "the list":

public Config Elements(Func<List<Element>> a) {
    List<Element> elements = a();
    foreach (Element e in elements) {
        this.elements.Add(e);
    }
    return this;
}

And here's how to use it:

config.Name("Foo")
    .Elements(() => new List<Element>() {
            new Element().Name("element1").Height(23),
            new Element().Name("element2").Height(31)
        })
    .Foo(3232);

Note that it presumes Element is not nested inside Config (or you'd need new Config.Element() in example 2).

Note that in your "the list" example, you've passed in a single Element object, but you're trying to set it twice. The second line will alter the Element, not create a new one.:

.Elements(e => {
                 e.Name("element1").Height(23); // <-- You set it
                 e.Name("element2").Height(31); // <-- You change it
              })
.Foo(3232);

Thus this syntax can't work.

How it works:

Func<T,U,...> is an anonymous function delegate that takes in all the parameters but one, and returns the last one. Action<T,U,...> is an anonymous function delegate that takes in all parameters. For example:

Func<int,string> f = i => i.ToString(); says "take in an int, return a string".

Action<int> f = i => string c = i.ToString(); says "take in an int, return nothing".

于 2012-05-03T21:48:29.113 に答える