隐式强制扩展方法

发布于 2024-10-27 21:25:44 字数 496 浏览 4 评论 0原文

我遇到过一种情况,我使用字符串 left、right 和 center,但每次都必须调用它们的扩展方法来抑制逗号(当我说抑制时,我实际上是想将它们用引号引起来,如下所示)用于 CSV 输出)。这是一个基本的例子:

public static string CommaSuppressor(this string str)
{
    return str.Contains(',') ? string.Concat("\"", str.Replace("\"", "\"\""), "\"") : str;
}

尽管当然很可能有更优雅、更有效的方法来做到这一点,但我可能没有防范边缘情况,毫无疑问社区会让我意识到这一点。

因此,对于我处理过的每个字符串,我实际上都想对其进行调用。当然,由于到处都有大量字段,这意味着我的代码中充斥着 myvar.CommaSuppressor()

有人能引导我朝着隐式调用 CommaSuppressor 的方向吗?

I've come across a case where I'm using strings left, right, and centre but having to call an extension method on them every single time to suppress commas (when I say suppress, I actually mean to wrap them in quotes as this is for CSV output). Here's a basic example:

public static string CommaSuppressor(this string str)
{
    return str.Contains(',') ? string.Concat("\"", str.Replace("\"", "\"\""), "\"") : str;
}

Although of course there's most likely far more elegant, and efficient ways of doing this, and I probably haven't protected against edge cases which no doubt the community will make me aware of.

So for every string I ever deal with, I actually want to call this on it. Of course with having tons of fields everywhere this means my code is littered with myvar.CommaSuppressor().

Could anyone sway me in a direction where CommaSuppressor is implicitly called?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

清风不识月 2024-11-03 21:25:44

我不确定它是否更好,但另一种方法是编写自己的类来保存字符串。在构造函数中,您可以处理逗号,这样当您访问值时,它们就会按照您的意愿进行转义。

I'm not sure it is any better, but a different approach would be to write your own class to hold the string. In the constructor you could deal with the commas so that when you access the value they are escaped as you wish.

对你而言 2024-11-03 21:25:44

您可以使用重载的 ToString() 方法创建自定义类。在使用 ToString() 方法真正获得处理后的字符串值之前,您可以进行大量自定义。但当然,它不会像原来的 System.String 那么灵活

You could create custom class with overloaded ToString() method. You could do much customization before you really get your processed string value with ToString() method. But of course, it won't be as flexible as original System.String of course

蓝戈者 2024-11-03 21:25:44

使用默认字符串类不可能实现这一点。我能想到的唯一方法是为 string 创建一个包装类,每次需要时调用此方法。

There is no possibility to achieve this with the default string class. The only way I can think of is to create a wrapper class for string that calls this method every time it is needed.

指尖凝香 2024-11-03 21:25:44

只在将字符串输出到 csv 时进行逗号抑制怎么样?

How about only doing the comma suppression at the point where you output the string to the csv?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文