UrlParameter.Optional到底是什么?

时间:2013-09-17 14:23:41

标签: asp.net-mvc

起初,我认为它被定义为某种枚举。但事实并非如此。

UrlParameter定义如下:

// Summary:
//     Represents an optional parameter that is used by the System.Web.Mvc.MvcHandler
//     class during routing.
public sealed class UrlParameter
{
    // Summary:
    //     Contains the read-only value for the optional parameter.
    public static readonly UrlParameter Optional;

    // Summary:
    //     Returns an empty string. This method supports the ASP.NET MVC infrastructure
    //     and is not intended to be used directly from your code.
    //
    // Returns:
    //     An empty string.
    public override string ToString();
}

ILSpy将实现显示为:

// System.Web.Mvc.UrlParameter
/// <summary>Contains the read-only value for the optional parameter.</summary>
public static readonly UrlParameter Optional = new UrlParameter();

那么当MVC看到以下代码时,怎么知道不将可选参数放入字典? 毕竟,下面的代码只是为ID分配了一个新的UrlParameter实例。

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

1 个答案:

答案 0 :(得分:6)

看看更广泛的背景。

UrlParameter的完整源代码是

public sealed class UrlParameter {

    [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "This type is immutable.")]
    public static readonly UrlParameter Optional = new UrlParameter();

    // singleton constructor
    private UrlParameter() { }

    public override string ToString() {
        return String.Empty;
    }
}

UrlParameter.Optional是唯一可能的UrlParameter实例 换句话说,整个UrlParameter类仅作为可选参数的占位符存在。