OptionalAttribute参数的默认值? [英] OptionalAttribute parameter's default value?

查看:174
本文介绍了OptionalAttribute参数的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN的VS2010 命名和可选参数(C#编程指南)告诉我们关于可选参数C#,显示出类似的代码,我期望:

 公共无效ExampleMethod(INT要求,
串optionalstr =默认串,
INT optionalint = 10)

好吧,但它也说:




您还可以使用.NET
OptionalAttribute类中声明可选
参数。
OptionalAttribute参数不
需要一个默认值




我读的MSDN's OptionalAttribute页面,并在线完成搜索(这说明很多人声称OptionalAttribute参数不能食用通过C# - 我猜这些评论之前,C#4发),但我无法找到答案的两个问题:



如果我用OptionalAttribute来?定义一个C#参数可选:




  1. 如果我认为这种方法并没有指定该参数的值是什么值将使用

  2. 将这个值在编译时或运行时?


解决方案
评估

的规则是这样的:




  • 对于类型参数对象,< A HREF =http://msdn.microsoft.com/en-us/library/system.type.missing.aspx> Type.Missing 是过去了。

  • 对于其他的引用类型,传递。

  • 对于值类型,值类型的默认传递。

    • 可空< T> ; 这意味着你会得到一个可空< T> 实例,这等于 的HasValue 属性将返回




请注意,在不同的类型参数的一切的情况下,对象,这是默认(T)相当于



我有点惊讶,因为的 C#4.0规范没有标明结局会是什么,我希望它在那里。



另外(如在评论斯科特Rippey表示 ),这是在编译时进行评估,这是不是一个运行时操作,这意味着,如果你有在其他组件此方法,已部署的呼叫,并更改可选值,默认传递到该方法将的的改变,除非你编译一切,使得反对装配方法调用。


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:

  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).

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.

这篇关于OptionalAttribute参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆