Jump to content

simple class C#


joecool2005

Recommended Posts

Hi,I'm a newbie of C#.I create a simple class Kid like this

<% @Page Language="C#" %><% @Import Namespace="System" %><script language="C#" runat="server">class Kid{	private int age;	private string name;	public Kid()	{		name = "N/A";	}	public Kid(string name, int age)	{		this.name = name;		this.age = age;	}	public void PrintKid()	{	  Response.Write("{0}, {1} years old.", name, age);	}} void Page_Load(object s, EventArgs e)	{		Kid kid1 = new Kid("Craig", 11);		Kid kid2 = new Kid("Sally", 10);		Kid kid3 = new Kid();		Response.Write("Kid #1:");		kid1.PrintKid();		Response.Write("<br>Kid #2: "+"<br>");		kid2.PrintKid();		Response.Write("<br>Kid #3: "+"<br>");		kid3.PrintKid();	}</script>

I'm not able to access on PrintKid() method. It showed an error Compiler Error Message: CS0038: Cannot access a nonstatic member of outer type 'System.Web.UI.Page' via nested type 'ASP.net2_myclass_aspx.Kid'What should I do?Thx

Link to comment
Share on other sites

Firstly I would recommend not having class variables the same name as function variables, it will be confusing.

class Kid{	private int mAge;	private string mName;	public Kid()	{		mName = "N/A";	}	public Kid(string name, int age)	{		mName = name;		mAge = age;	}	public void PrintKid()	{	  Response.Write("{0}, {1} years old.", mName, mAge);	}

try this

Link to comment
Share on other sites

The main problem here is that you are trying to access the Response object from inside of the Kid class when that class it totally oblivious to it. Try changing your PrintKid method to this:

public string PrintKid(){	return String.Format("{0}, {1} years old.", this.name, this.age);}

And then, in your Page_Load handler, change it to this:

Response.Write("Kid #1:");Response.Write(kid1.PrintKid());Response.Write("<br>Kid #2: "+"<br>");Response.Write(kid2.PrintKid());Response.Write("<br>Kid #3: "+"<br>");Response.Write(kid3.PrintKid());

EDIT: Considering the above changes, it would probably make more sense to call the PrintKid method "ToString".EDIT2: Or, ignore everything I said and change Response.Write() in the PrintKid method to:

System.Web.HttpContext.Current.Response.Write(String.Format("{0}, {1} years old.", this.name, this.age));

Link to comment
Share on other sites

I'd go with #2, I didn't even pick up on the Response problem
I didn't at first either. I don't do scripts that are runat=server. Nor do I typically build classes in an .aspx page.If I'm building C# that will run on the page, I put that code in a code behind. If I'm building classes, I put them in .cs files either in the App_Code directory of the Website or in a separate Class Library project.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...