gpt4 book ai didi

常规闭包参数

转载 作者:行者123 更新时间:2023-12-04 17:59:46 25 4
gpt4 key购买 nike

this book 中出现了以下使用 grails 邮件插件提供的 sendMail 方法的示例.

sendMail {
to "foo@example.org"
subject "Registration Complete"
body view:"/foo/bar", model:[user:new User()]
}

我知道 {} 中的代码是一个作为参数传递给 sendMail 的闭包。我也明白 to , subjectbody是方法调用。

我试图弄清楚实现 sendMail 方法的代码是什么样的,我最好的猜测是这样的:
MailService {

String subject
String recipient
String view
def model

sendMail(closure) {
closure.call()
// Code to send the mail now that all the
// various properties have been set
}

to(recipient) {
this.recipient = recipient
}

subject(subject) {
this.subject = subject;
}

body(view, model) {
this.view = view
this.model = model
}
}

这是合理的,还是我错过了什么?特别是闭包中调用的方法( tosubjectbody )是否必须与 sendMail 属于同一类的成员? ?

谢谢,
大学教师

最佳答案

MailService.sendMail 闭包委托(delegate):

 MailMessage sendMail(Closure callable) {
def messageBuilder = new MailMessageBuilder(this, mailSender)
callable.delegate = messageBuilder
callable.resolveStrategy = Closure.DELEGATE_FIRST
callable.call()

def message = messageBuilder.createMessage()
initMessage(message)
sendMail message
return message
}

例如,MailMessageBuilder 的方法:
void to(recip) {
if(recip) {
if (ConfigurationHolder.config.grails.mail.overrideAddress)
recip = ConfigurationHolder.config.grails.mail.overrideAddress
getMessage().setTo([recip.toString()] as String[])
}
}

关于常规闭包参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/875941/

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