这里发生了什么事?什么样的成员是“可选的”?

时间:2016-07-10 12:47:32

标签: c# asp.net .net asp.net-mvc

任何人都可以告诉我下面的代码中发生了什么。将成员声明为类类型的原因是什么?

    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();
}

我在路线注册方法中看到了它:

routes.MapRoute(                 名称:“默认”,                 url:“{controller} / {action} / {id}”,                 默认值:new {controller =“Home”,action =“AboutView1”,id = UrlParameter.Optional}             );

1 个答案:

答案 0 :(得分:2)

虽然这可能看起来很奇怪,但Optional字段只不过是单例设计模式(see Static Initialization here)的实现。在这种情况下非常特别。

由于该字段标记为static,因此您的应用程序中只有UrlParameter类的一个实例。 readonly修饰符意味着对此字段的赋值只能作为声明的一部分或在同一个类(have a look here)的构造函数中出现。在此具体示例中,Optional始终设置为null(see here)。所以它是一个单例,但只是一个常量,因为它被定义为null。

Microsoft可能已经这样做,以便将来Optional字段的值可能会发生变化而不会破坏现有代码(see the difference between const and static readonly) - const会强制您重新编译所有现有代码,如果发生变化,要使其再次起作用,而static readonly则不然。

相关问题