可选的非系统类型参数
C#4.0 带来了可选参数,我已经等了很长一段时间了。然而,似乎因为只有系统类型可以是 const,所以我无法使用我创建的任何类/结构作为可选参数。
有没有某种方法可以让我使用更复杂的类型作为可选参数。或者这是人们必须忍受的现实之一?
C#4.0 brings optional parameters, which I've been waiting for for quite some time. However it seems that because only System types can be const
, I cannot use any class/struct which I have created as an optional parameter.
Is there a some way which allows me to use a more complex type as an optional parameter. Or is this one of the realities that one must just live with?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于引用类型,我能想到的最好的办法是:
您可以通过使参数可为空来对结构使用相同的想法:
The best I could come up with for reference types was:
You can use the same idea for structs by making the parameter nullable:
您可以使用任何类型作为可选参数:
好的,我重读了您的问题,我想我明白您的意思 - 您希望能够执行以下操作:
不幸的是,这是不允许的,因为默认参数的值必须在编译时已知,以便编译器可以将其烘焙到程序集中。
You can use any type as an optional parameter:
Okay, I reread your question and I think I see what you mean - you want to be able to do something like this:
Unfortunately this is a not allowed since the value of the default parameter must be known at compile time so that the compiler can bake it into the assembly.