Square bracket syntax in function's parameter

2020-08-09 09:38发布

问题:

I'm learning ASP.NET and stumbled upon this method declaration:

public IQueryable<Product> GetProducts([QueryString("id")] int? categoryId) {.....}

The tutorial said categoryId will be equal to query string "id" (From URL, like &id=5) but the question is what is [QueryString("id")] syntax called? Is this usable outside ASP.NET and what will the application of this be?

回答1:

That's applying the QueryStringAttribute attribute to the parameter categoryId. It's just an attribute, just like the ones you're probably more used to seeing on methods or classes, like this:

[STAThread]
static void Main()
{
}

In this case, presumably some part of the framework (I'm not an ASP.NET developer, so I can't point out exactly what) is using reflection to find all the methods, find any QueryStringAttribute values applied to the parameters, and then matching the names within those attributes with the names in the query string, then extracting the matching values to pass into the method call (again using reflection).



标签: c# asp.net