C# - make a string print to console differently but be used elsewhere in its original form
I have a weird question. Here it goes -
Let's consider the below code snippet:
string test ="this is a test string";
Console.WriteLine(test);
I want it to print a different thing - like yup, this is a test string
. Actually, I want to see if the string is matching some pattern, and if so 开发者_JS百科I want it printed differently. I want that to be the case only when I am printing it to console, but whenever I am using it elsewhere, it should be the original one.
I was hoping I could write an extension method on String class ( or Object class? ) and make ToString() return as per my needs, but the docs say:
An extension method will never be called if it has the same signature as a method defined in the type.
Is there any possibility of doing such a thing? I cannot use a new type. Or maybe trying to make ToString() behave differently is not the way to go. But is there a way to make a particular string print to the console differently but be used in its original form elsewhere?
You could do something like this:
public static class StringExtension
{
public static void WriteToConsole(this string text)
{
string result;
if (<matches1>)
result = "111";
else if (<matches1>)
result = "222";
Console.WriteLine(result);
}
}
And the usage would be:
string test = "this is a test string";
test.WriteToConsole();
Technically, you can implement IFormatProvider and pass it to Console.WriteLine
.
To make it use by default you can try to make custom [CultureInfo] ( http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx) and set it to be used by your app.
Never tried this, so caveat emptor.
精彩评论