For instance if I'm inside the Page_Load method and I want to get query string data I just do this:
public partial class Product_Detail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["p"];
}
}
but if I am inside the class, but not within any method I have to use:
public partial class Product_Detail : System.Web.UI.Page
{
string id = HttpContext.Current.Request.QueryString["p"];
protected void Page_Load(ob开发者_Python百科ject sender, EventArgs e)
{
}
}
Why is that?
Member variable initialisers - which is what your id
assignment is -- can't use instance methods or properties. Page.Request is an instance property, and therefore isn't available to member initialisers.
I would surmise it is because class members are not created until the class is instantated. Because of this you cannot access the Request property except within your class methods.
Properties of the current class (including this) are not accessible until the constructor. Since field initializers happen before the constructor is executed, properties (and fields, and methods) are not accessible.
You cannot refer to an instance's properties for a field's initializer—when the field is initialized the instance isn't fully constructed yet (i.e., there's no this
pointer).
精彩评论