{ Element.Name("elemen-6ren">
gpt4 book ai didi

c# - 创建用于将元素添加到列表的流畅界面

转载 作者:太空狗 更新时间:2023-10-30 00:01:49 24 4
gpt4 key购买 nike

这就是我要实现的目标:

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; }
}
}

有人知道怎么做吗?

最佳答案

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)
}
)

关于c# - 创建用于将元素添加到列表的流畅界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10347678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com