Calling ToString() gotchas
I have read that ToSt开发者_如何学Goring() uses reflection (although it should just put quotation marks around the object it is called on so I don't know where/why it may use reflection). Is there any proof of this? And is there any performance penalty of calling .ToString() (maybe I should call Convert.ToString()?)?
If you don't override the ToString()
method, you end up calling Object.ToString()
, whose implementation looks something like this:
public virtual string ToString()
{
return this.GetType().ToString();
}
[MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical]
public extern Type GetType();
The method doesn't simply "put quotation marks around the object it is called on". In order to accomplish that result, it must reflectively get the runtime type information and call ToString()
on that, which in turn looks something like this:
public override string ToString()
{
return ("Type: " + this.Name);
}
Anytime you go through reflection for something there is a bit of a performance penalty, but in this case probably not one large enough to really matter - unless you are doing it inside of a very tight, very large loop.
Are you seeing a performance problem? What are you trying to accomplish that is leading you to want to call Object.ToString()
rather than calling an overridden version that you provide?
I think that if you don't override ToString() that is where it ends up using reflection.
If you had:
public class SomeObject
{
public void SomeMethod();
}
void program
{
SomeObject o = new SomeObject();
Console.WriteLine(o.ToString());
}
You would have to use reflection to know what type of object o is. Now, if you override ToString() which you should do to have a meaningful string representation, then the code you write will get called directly w/o reflection.
精彩评论