简体   繁体   English

MVC3对C#可选参数有什么作用?

[英]What does MVC3 do with C# Optional Parameters?

Setup the following Controller 设置以下控制器

public class HomeController : Controller
{
    // GET: /Home/Read    
    public string Read(Sample sample = null)
    {
        if (sample != null)
            Console.WriteLine("Not null");
        else
            Console.WriteLine("null");

        return "";
    }

}
public class Sample
{

}

Sample is not null . Sample 不为null Is this a bug or a feature? 这是错误还是功能?

Optional parameters are implemented via call-site rewriting . 可选参数通过呼叫现场重写实现 Since the controller will be invoked using a full parameter list by the MVC engine, the optional parameter is simply not relevant. 由于MVC引擎将使用完整的参数列表来调用控制器,因此可选参数根本不相关。

For example, given the following function: 例如,给定以下功能:

public void Foo(int bar = 1, int baz = 2)
{
}

Calling it like so: 像这样调用它:

Foo();

Causes the compiler to actually interpret it as: 使编译器将其实际解释为:

Foo(1, 2);

There is no magic that occurs whereby the call remains as Foo() , and then the method itself subs in the parameters at run-time. 调用保持为Foo() ,然后方法本身在运行时包含在参数中,不会发生魔术。 The parameters are subbed in at compile-time, and nothing futher needs to be done. 这些参数在编译时被嵌入,并且无需执行任何其他操作。

Update : To indicate to MVC that a given route parameter is optional, you can set it to UrlParameter.Optional when defining your route. 更新 :要向MVC指示给定的路由参数是可选的,可以在定义路由时将其设置为UrlParameter.Optional At that point, the default parameter value of the action method should kick in. 此时,应该使用action方法的默认参数值。

Its a feature not a bug. 它的功能不是错误。 The binder sees that method signature is the only one that makes sense (if you define one with no parameter I'd imagine that would be called instead or you would get the 'ambiguous call' error) and creates an empty instance since there are no query string parameters available. 活页夹认为方法签名是唯一有意义的方法(如果您定义一个不带参数的对象,我会想象会被调用,否则会收到“模棱两可的调用”错误),并创建一个空实例,因为没有查询字符串参数可用。 Since its the model binder doing the magic of creating your instance and not the compiler here, it's MVC's doing. 由于它的模型绑定器可以创建实例而不是这里的编译器,所以它是MVC。

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

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