VS 2010和VS 2008中optionalAttribute(用于声明可选参数)的行为差异 [英] difference in the behavior of optionalAttribute (used to declare an optional parameter) in VS 2010 vs VS 2008

查看:47
本文介绍了VS 2010和VS 2008中optionalAttribute(用于声明可选参数)的行为差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的C#方法,带有使用OptionalAttribute as声明的可选参数

A simple C# method with an optional parameter declared using the OptionalAttribute as

namespace  ClassLibrary11
{
   public class Class1
   {
      public int Foo(int a, int b, [Optional] int c)
      {
         return a + b + c;
      }
   }
}

在VS 2010上. obj.Foo(3,4)输出预期的 7 .但是,在VS 2008或更低版本上不能使用,除非使用DefaultParameterValue Attribute提供一些默认值.因此,在VS2008或之前调用 Foo(3,4)会导致错误:

On VS 2010. obj.Foo(3,4) outputs 7 as expected. But not on VS 2008 or before unless there is some default value is provided using DefaultParameterValue Attribute. So a call to Foo(3,4) on VS2008 or before results into an error:

类型为'System.Reflection.Missing'的对象不能转换为类型为'System.Double'

在VS 2008和VS 2010上,如果都使用反射来调用方法Foo,那么如果未为可选参数提供默认值,它将引发相同的错误.

On both VS 2008 and VS 2010, if reflection is used to invoke method Foo, then it throws the same error if the default value is not provided for the optional parameter.

ClassLibrary11.Class1 cls = new ClassLibrary11.Class1();
MethodInfo mi = typeof(ClassLibrary11.Class1).GetMethod("Foo");
Object[] objarr = new Object[] {1,2, Missing.Value}; 
Object res = mi.Invoke(cls, objarr);

所以问题是:

那么VS 2010编译器如何将默认值分配给可选参数,而框架4.0却不是通过反射实现的?

So how is that VS 2010 compiler takes care of assigning the default value to the optional parameter but the framework 4.0 does not via reflection?

推荐答案

简而言之,这是因为C#3.5不支持可选参数.根据 MSDN

simply put, it's because C# 3.5 doesn't support optional parameters. As per MSDN,

请注意,DefaultParameterValueAttribute不会为不支持此功能的语言添加对默认参数的支持.例如,如果将DefaultParameterValueAttribute与不支持默认参数的用C#编写的方法一起使用,则从C#调用该方法时将无法使用默认参数.

Note that the DefaultParameterValueAttribute does not add support for default parameters to languages that do not support this feature. For example, if you use the DefaultParameterValueAttribute with a method written in C#, which does not support default parameters, you cannot use the default parameter when calling the method from C#.

这篇关于VS 2010和VS 2008中optionalAttribute(用于声明可选参数)的行为差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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