可选属性参数的默认值?
MSDN 的 VS2010 命名参数和可选参数(C# 编程指南) 告诉我们 C# 中的可选参数,显示了我期望的代码:
public void ExampleMethod(int required,
string optionalstr = "default string",
int optionalint = 10)
好的,但它还说:
您还可以声明可选 使用 .NET 的参数 可选属性类。 可选属性参数不 需要默认值。
我阅读了MSDN的OptionalAttribute页面,并完成在线搜索(显示很多人声称 C# 无法使用OptionalAttribute 参数——我猜这些评论是在 C# 4 之前做出的?),但我找不到两个问题的答案:
如果我使用OptionalAttribute将 C# 参数定义为可选:
- 如果我调用该方法并且不指定该参数的值,将使用什么值?
- 该值会在编译时还是运行时评估?
MSDN's VS2010 Named and Optional Arguments (C# Programming Guide) tells us about optional parameters in C#, showing code like I'd expect:
public void ExampleMethod(int required,
string optionalstr = "default string",
int optionalint = 10)
Ok, but it also says:
You can also declare optional
parameters by using the .NET
OptionalAttribute class.
OptionalAttribute parameters do not
require a default value.
I read MSDN's OptionalAttribute page, and done searches online (which shows lots of people claiming OptionalAttribute parameters can't be consumed by C# -- I'm guessing these comments were made before C# 4?), but I can't find the answer to two questions:
If I use OptionalAttribute to define a C# parameter as optional:
- what value will be used if I call that method and don't specify that parameter's value?
- will that value be evaluated at compile time or runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
规则如下:
object
类型的参数,Type.Missing
已传递。null
。可为空
这意味着您将获得一个Nullable
实例,它等于null
(HasValue
属性 将返回false
)请注意,除了参数之外的所有内容
object
类型,它相当于default(T)
。我有点惊讶,因为 C# 4.0 规范 没有表明结果是什么,我希望它会在那里。
另外(正如 Scott Rippey 在评论中指出的那样),这是在以下位置进行评估的:编译时,这不是运行时操作,这意味着如果您在已部署的其他程序集中调用此方法,并且更改了可选值,则传递给该方法的默认值将不会 除非您编译对程序集中的方法进行调用的所有内容,否则会发生更改。
The rules are this:
object
,Type.Missing
is passed.null
is passed.Nullable<T>
this means that you will get aNullable<T>
instance which is equal tonull
(theHasValue
property will returnfalse
)Note that in the case of everything except parameters of type
object
, it's the equivalent ofdefault(T)
.I was a little surprised, as the C# 4.0 specification didn't indicate what the outcome would be, and I'd expect it to be there.
Also (as indicated by Scott Rippey in the comments), this is evaluated at compile-time, this is not a run-time operation, meaning that if you have calls to this method in other assemblies which are already deployed, and you change the optional value, the default passed to the method will not change unless you compile everything that makes the call against the method in the assembly.