首页 文章

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

提问于
浏览
0

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

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(name:“Default”,url:“ / / ”,默认值:new {controller =“Home”,action =“AboutView1”,id = UrlParameter.Optional});

1 回答

  • 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 不“T .

相关问题