简体   繁体   English

OptionalAttribute 参数的默认值?

[英]OptionalAttribute parameter's default value?

MSDN's VS2010 Named and Optional Arguments (C# Programming Guide) tells us about optional parameters in C#, showing code like I'd expect: MSDN 的 VS2010 命名和可选参数(C# 编程指南)告诉我们 C# 中的可选参数,显示的代码与我期望的一样:

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.您还可以使用 .NET OptionalAttribute 类声明可选参数。 OptionalAttribute parameters do not require a default value. OptionalAttribute 参数不需要默认值。

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:我阅读了MSDN 的 OptionalAttribute 页面,并在线进行了搜索(这表明很多人声称 C# 不能使用 OptionalAttribute 参数——我猜这些评论是在 C# 4 之前做出的?),但我找不到答案两个问题:

If I use OptionalAttribute to define a C# parameter as optional:如果我使用 OptionalAttribute 将 C# 参数定义为可选:

  1. what value will be used if I call that method and don't specify that parameter's value?如果我调用该方法而不指定该参数的值,将使用什么值?
  2. will that value be evaluated at compile time or runtime?会在编译时或运行时评估该值吗?

The rules are this:规则是这样的:

Note that in the case of everything except parameters of type object , it's the equivalent of default(T) .请注意,对于除object类型的参数之外的所有内容,它等效于default(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.我有点惊讶,因为C# 4.0 规范没有说明结果会是什么,我希望它在那里。

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.此外(如Scott Rippey 在评论中指出的),这是在编译时评估的,这不是运行时操作,这意味着如果您在其他已部署的程序集中调用了此方法,并且您更改了可选值,除非您编译对程序集中的方法进行调用的所有内容,否则传递给该方法的默认值不会更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM