Skip to main content
 首页 » 编程设计

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

2024年02月23日24findumars

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

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

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