gpt4 book ai didi

C# - 使字符串以不同的方式打印到控制台,但以其原始形式在其他地方使用

转载 作者:太空宇宙 更新时间:2023-11-03 22:12:25 26 4
gpt4 key购买 nike

我有一个奇怪的问题。就这样——

让我们考虑下面的代码片段:

string test ="this is a test string";
Console.WriteLine(test);

我想让它打印不同的东西——比如是的,这是一个测试字符串。实际上,我想看看字符串是否与某种模式匹配,如果是,我希望它以不同的方式打印。我希望只有当我将它打印到控制台时才是这种情况,但无论何时我在其他地方使用它,它都应该是原始的。

我希望我可以在 String 类(或 Object 类?)上编写一个扩展方法,并根据我的需要使 ToString() 返回,但文档说:

An extension method will never be called if it has the same signature as a method defined in the type.

有没有可能做这样的事情?我不能使用新类型。或者也许尝试使 ToString() 的行为不同并不是可行的方法。但是有没有办法使特定字符串以不同方式打印到控制台,但在其他地方以其原始形式使用?

最佳答案

你可以这样做:

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);
}
}

用法是:

string test = "this is a test string";
test.WriteToConsole();

关于C# - 使字符串以不同的方式打印到控制台,但以其原始形式在其他地方使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6165911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com