C# - 以不同的方式将字符串打印到控制台,但以其原始形式在其他地方使用
我有一个奇怪的问题。就这样 -
让我们考虑下面的代码片段:
string test ="this is a test string";
Console.WriteLine(test);
我希望它打印不同的东西 - 就像是的,这是一个测试字符串
。实际上,我想看看该字符串是否与某些模式匹配,如果是,我希望它以不同的方式打印。我希望只有当我将其打印到控制台时才是这种情况,但每当我在其他地方使用它时,它都应该是原始的。
我希望我可以在 String 类(或 Object 类?)上编写一个扩展方法,并使 ToString() 根据我的需要返回,但文档说:
扩展方法永远不会 如果它具有相同的签名,则调用 类型中定义的方法。
有可能做这样的事情吗?我无法使用新类型。或者也许尝试让 ToString() 表现不同并不是正确的方法。但是有没有办法让特定的字符串以不同的方式打印到控制台,但在其他地方以其原始形式使用?
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从技术上讲,您可以实现 IFormatProvider 并将其传递给
Console.WriteLine
。要使其默认使用,您可以尝试自定义 [CultureInfo] ( http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx)并将其设置为由您的应用程序使用。
从来没有尝试过这个,所以买者自负。
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.
你可以这样做:
用法是:
You could do something like this:
And the usage would be: