可选参数的默认值是否必须是静态的?(Do default values for optional parameters have to be static?)

编程入门 行业动态 更新时间:2024-10-27 08:26:30
可选参数的默认值是否必须是静态的?(Do default values for optional parameters have to be static?)

我有一些功能,我可以实现使用方法重载/链,但我想知道如果我可以实现与可选参数相同的功能。 下面是我想要实现的一个例子,下面是一个包含方法链接的版本(希望这会使我的意图变得清晰)。 这可以使用可选参数完成吗?

// what I would like to do private string CreateMessageFromTemplate(string templateId, Contact contact, string email = contact.emails.FirstOrDefault()) { ... } //what I know I can do private string CreateMessageFromTemplate(string templateId, Contact contact) { CreateMessageFromTemplate(templateId, contact, contact.emails.FirstOrDefault()); } private string CreateMessageFromTemplate(string templateId, Contact contact, string email) { ... }

正如你所看到的,我从联系人参数中得到默认值(如果你不给我一个特定的电子邮件,我只会使用列表中的第一个)。 可选参数的默认值是否必须是静态的,或者它们可以是像我的例子中那样的表达式的结果? 如果可以,那么正确的语法是什么?

I have some functionality that I could implement using method overloading/chaining but I'm wondering if I can achieve the same functionality with optional parameters. Here is an example of what I would to like achieve, below it is a version with method chaining (hopefully that will make my intent clear). Can this be done using optional parameters?

// what I would like to do private string CreateMessageFromTemplate(string templateId, Contact contact, string email = contact.emails.FirstOrDefault()) { ... } //what I know I can do private string CreateMessageFromTemplate(string templateId, Contact contact) { CreateMessageFromTemplate(templateId, contact, contact.emails.FirstOrDefault()); } private string CreateMessageFromTemplate(string templateId, Contact contact, string email) { ... }

As you can see, I derive the default value from the contact argument (if you don't give me a specific email, I'll just use the first one in the list). Do the default values of optional parameters have to be static or can they be the result of an expression like in my example? If they can, what is the proper syntax?

最满意答案

参数的默认值必须是编译时常量。 你可以做的是使默认为空,然后在函数中设置它:

private string CreateMessageFromTemplate(string templateId, Contact contact, string email = null) { email = email ?? contact.emails.FirstOrDefault()) ... }

The default value for an argument has to be a compile-time constant. What you can do though, is make the default null, and then set it in the function:

private string CreateMessageFromTemplate(string templateId, Contact contact, string email = null) { email = email ?? contact.emails.FirstOrDefault()) ... }

更多推荐

本文发布于:2023-08-06 20:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455033.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   静态   默认值   参数   default

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!