Hi I have the Default aspx. I want to test overriding default methods like to ToString(). Whenever I use ToString(), I thought with following code it has to add "my text";? why not?
public partial class test : System.Web.UI.Page
{
开发者_开发百科 public override string ToString()
{
return base.ToString() + "my text";
}
protected void Page_Load(object sender, EventArgs e)
{
object test = 3333;
Response.Write( test.ToString());
}
}
You want to call
this.ToString();
or simply
ToString();
What you did created an object
with the name test
, not the type test
, and called the default ToString
of object
(well, of int
, in this case).
Alternatively, if you want to create another page with the type test
:
test newPage = new test();
test.ToString();
As everyone said you are overriding the wrong method. If I understand correctly what you are trying to accomplish, then maybe an extension method is more appropriate :
public static class ObjectExtensions
{
public static string ToCustomString(this object instance)
{
return instance.ToString() + "whatever";
}
}
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
object test = 3333;
Response.Write(test.ToCustomString());
}
}
The object test
is not your class, it's just an object.
I would like you to rewrite your code in
protected void TestWrite(object sender, EventArgs e)
{
test test = new test();
System.Diagnostics.Trace.Write(test.ToString());
}
and then write
protected void TestWrite(object sender, EventArgs e)
{
test test = new test();
object testObject = test;
System.Diagnostics.Trace.Write(testObject.ToString());
}
You will call ever the overwritten tostring method.
We call it "dynamic binding" in object oriented programming. Please be confident about this subject if you want to understand what really means an Object in computer science.
And... as Unsliced said :
"The object test is not your class, it's just an object."
Good Luck
精彩评论