11

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

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 }
4

1 回答 1

7

看看更广泛的背景。

完整的源代码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类仅作为可选参数的占位符存在。

于 2013-09-17T14:26:40.267 回答