"Effective C #" Item 5: Provides a meaningful TSTRING function

xiaoxiao2021-03-30  205

When writing a custom type, even if we don't write the toString function, the system will automatically provide a TSTRING function, for example:

Public Class Clsuserinfo

{

Private string strusename;

......

}

However, the TOSTRING function is provided, does not do too much things, can not real reflect some of the current object, as this code, call toString returned to String is the same. Then this return value does not make much sense for the caller.

In order to provide a meaningful TSTRING function, you need to overload the toString function to implement a toString function for this object. For example, for the type above CLSUSERINFO, this kind of writing will make the toString function more meaningful.

Public Class Clsuserinfo

{

Private string strusename;

......

Public override string toString ()

{

Return String.Format ("User Name: {0}", StruserName);

}

}

Provide a meaningful toString function, which is useful for debugging or publishing this class because this approach is the easiest way, relative to the member properties of the Access class and then combines strings. However, when you write the code, including me, often ignore the meaningful Tostring function, which seems to be improved in the future.

In addition to the toString function provided by the overload system, you can inherit the iFormatTable interface in C # to provide more complex Tostring functions. As for this, I don't want to say more, because inheriting the interface, there will be a lot of changes. This may only be more profound in real apps.

转载请注明原文地址:https://www.9cbs.com/read-130551.html

New Post(0)