用 C# 编写我的第一个 DSL,并沉迷于 func&行动
我正在尝试为工作中的一个简单工具编写我的第一个 DSL。我正在使用构建器模式来设置复杂的父对象,但在构建父对象的子集合时遇到了困难。这是一个示例:
使用:
var myMorningCoffee = Coffee.Make.WithCream().WithOuncesToServe(16);
带有闭包的示例(我认为这就是它们的名称):
var myMorningCoffee = Coffee.Make.WithCream().PourIn(
x => {
x.ShotOfExpresso.AtTemperature(100);
x.ShotOfExpresso.AtTemperature(100).OfPremiumType();
}
).WithOuncesToServe(16);
示例类(没有子 PourIn() 方法,因为这是我想要弄清楚的。)
public class Coffee
{
private bool _cream;
public Coffee Make { get new Coffee(); }
public Coffee WithCream()
{
_cream = true;
return this;
}
public Coffee WithOuncesToServe(int ounces)
{
_ounces = ounces;
return this;
}
}
所以在我的工作应用程序中,我构建复杂的对象就好了,但我一生都无法弄清楚如何为父对象上的子集合编码 lambda。 (在本例中是浓缩咖啡的镜头(子集合))。
也许我在这里混淆了概念,但我不介意被澄清;然而,我真的很喜欢它的读法,并且想弄清楚如何让它发挥作用。
谢谢, 山姆
I'm taking a crack at writing my first DSL for a simple tool at work. I'm using the builder pattern to setup the complex parent object but am running into brick walls for building out the child collections of the parent object. Here's a sample:
Use:
var myMorningCoffee = Coffee.Make.WithCream().WithOuncesToServe(16);
Sample with closure (I think that's what they're called):
var myMorningCoffee = Coffee.Make.WithCream().PourIn(
x => {
x.ShotOfExpresso.AtTemperature(100);
x.ShotOfExpresso.AtTemperature(100).OfPremiumType();
}
).WithOuncesToServe(16);
Sample class (without the child PourIn() method as this is what I'm trying to figure out.)
public class Coffee
{
private bool _cream;
public Coffee Make { get new Coffee(); }
public Coffee WithCream()
{
_cream = true;
return this;
}
public Coffee WithOuncesToServe(int ounces)
{
_ounces = ounces;
return this;
}
}
So in my app for work I have the complex object building just fine, but I can't for the life of me figure out how to get the lambda coded for the sub collection on the parent object. (in this example it's the shots (child collection) of expresso).
Perhaps I'm confusing concepts here and I don't mind being set straight; however, I really like how this reads and would like to figure out how to get this working.
Thanks,
Sam
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的,我想出了如何使用附加表达式生成器来编写 DSL。这就是我希望 DSL 的阅读方式:
这是我通过的测试:
这是我的 CoffeeExpressionBuilder DSL 类:
欢迎任何和所有建议。
Ok, so I figured out how to write my DSL using an additional expression builder. This is how I wanted my DSL to read:
Here's my passing test:
And here's my CoffeeExpressionBuilder DSL class(s):
Any and all suggestions are welcome.
如果 .IncludeApps 接受 AppRegistrations 数组
,那么
最终它会看起来像这样......
在您的 IncludeApps 方法中,您将检查注册并根据需要创建对象。
What if .IncludeApps accepted an array of AppRegistrations
then
so eventually it would look like this...
Inside your IncludeApps method you would inspect the registrations and create the objects as required.
要走委托路线,也许这样的事情会起作用?
如果您没有设置委托路线,也许参数可以工作?
To go the delegate route maybe something like this would work?
If you aren't set on the delegate route maybe params would work?