What's happening here? What kind of member is "Optional"?
Can anyone tell me what is happening in below code. What is the reason behind declaring a member as the class type ??
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();
}
I saw it in the route registration method:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "AboutView1", id = UrlParameter.Optional } );
Although this may look strange to you, the Optional
field is nothing but an implementation of the singleton design pattern (see Static Initialization here). A very special one in this case.
Because the field is marked as static
, you'll only have one instance of the UrlParameter
class in your application. The readonly
modifier means that assignments to this field can only occur as part of the declaration or in a constructor in the same class (have a look here). In this concrete example, Optional
is always set to null (see here). So it is a singleton, but merely a constant because it's defined as null.
Microsoft has probably done this so that the value of the Optional
field may change in the future without breaking existing code (see the difference between const
and static readonly
) - const
forces you to recompile all your existing code, in case of change, to make it work again, while static readonly
doesn't.
上一篇: 算法的名称