c# - .NET 相当于旧的 vb left(string, length) 函数

标签 c# .net vb.net

作为一名非 .NET 程序员,我正在寻找与旧的 Visual Basic 函数 left(string, length) 等效的 .NET。它很懒惰,因为它适用于任何长度的字符串。正如预期的那样,left("foobar", 3) = "foo" 而最有帮助的是 left("f", 3) = "f"

在 .NET 中 string.Substring(index, length) 对超出范围的所有内容抛出异常。在 Java 中,我总是手边有 Apache-Commons lang.StringUtils。在 Google 中,我没有深入搜索字符串函数。


@Noldorin - 哇,感谢您的 VB.NET 扩展!我第一次遇到,虽然我花了几秒钟在 C# 中做同样的事情:

public static class Utils
{
    public static string Left(this string str, int length)
    {
        return str.Substring(0, Math.Min(length, str.Length));
    }
}

注意静态类和方法以及 this 关键字。是的,调用它们就像 "foobar".Left(3) 一样简单。另见 C# extensions on MSDN .

最佳答案

这是一个可以完成这项工作的扩展方法。

<System.Runtime.CompilerServices.Extension()> _
Public Function Left(ByVal str As String, ByVal length As Integer) As String
    Return str.Substring(0, Math.Min(str.Length, length))
End Function

这意味着您可以像使用旧的 VB Left 函数(即 Left("foobar", 3) )或使用更新的 VB.NET 语法一样使用它,即

Dim foo = "f".Left(3) ' foo = "f"
Dim bar = "bar123".Left(3) ' bar = "bar"

关于c# - .NET 相当于旧的 vb left(string, length) 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/844059/

相关文章:

c# - 任务并行库 (TPL) 中的线程同步

c# - 在 .net 中的 lock 语句中调用 Thread.Sleep()

c# - 如何更正通用排序代码以对可空类型进行排序

c# - ASP.NET Core 1.0 (vNext) 中的引用库

.net - 如何使用 RS256 算法为 JWT 生成私有(private)和公共(public)证书?

asp.net - UpdatePanel崩溃,其他更新面板不起作用

c# - 如何将 GridView 绑定(bind)到复杂对象

c# - 基于字符数的字符串拆分

C# 与 VB.NET 按位或

c# - C# 扩展方法不允许通过引用传递参数吗?