这是什么做MVC3用C#中的可选参数? [英] What does MVC3 do with C# Optional Parameters?

查看:128
本文介绍了这是什么做MVC3用C#中的可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置以下控制器

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. Is this a bug or a feature?

推荐答案

可选参数通过实施的调用现场重写的。由于控制器将采用全参数列表的MVC引擎被调用,可选参数仅仅是不相关的。

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.

例如,考虑下面的函数:

For example, given the following function:

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

调用它像这样:

Foo();

使编译器实际上是间preT它为:

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. The parameters are subbed in at compile-time, and nothing futher needs to be done.

更新:要指示MVC一个给定的路径参数是可选的,可以将其设置为 UrlParameter.Optional 定义你的路由时。在这一点上,操作方法的默认参数值应该在踢。

Update: To indicate to MVC that a given route parameter is optional, you can set it to UrlParameter.Optional when defining your route. At that point, the default parameter value of the action method should kick in.

这篇关于这是什么做MVC3用C#中的可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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