gpt4 book ai didi

C# 8 从字符串中获取最后 n 个字符的方法

转载 作者:行者123 更新时间:2023-12-05 01:07:33 44 4
gpt4 key购买 nike

最近 VS 提示我使用:

var str = "foo";
var str2 = str[^2..];

而不是:

var str = "foo";
var str2 = str.Substring(str.Length - 2);

所以,我的问题是 str[^2..]str.Substring(str.Length - 2) 之间有什么区别吗?我认为这是一个新的 C# 功能,但我找不到任何关于它的文档。所以,我不知道它是怎么调用的,它是什么版本的C#。

这是我试图用谷歌搜索的内容:

^ in string access c#

我没有得到任何相关结果。我应该谷歌其他东西吗?

最佳答案

其他是正确的,因为它只是语法糖,但有一些细微的差别。它们都称为“子字符串”,但帽子版本调用 String.Substring(Int32, Int32) 签名,而后来的常规版本调用 String.Substring(Int32) 签名。

有趣的是,尽管 str[^2..] 生成了更多代码,但在我的快速基准测试中它的性能似乎稍好一些。

var str = "foo";
var str2 = str[^2..];
========generates the following IL=============
nop
ldstr "foo"
stloc.0 // str
ldloc.0 // str
dup
callvirt String.get_Length ()
dup
ldc.i4.2
sub
stloc.2
ldloc.2
sub
stloc.3
ldloc.2
ldloc.3
callvirt String.Substring (Int32, Int32)
stloc.1 // str2
ldloc.1 // str2
call Console.WriteLine (String)
nop
ret

还有下面的常规版本。

var str = "foo";
var str2 = str.Substring(str.Length - 2);
========generates the following IL=============
nop
ldstr "foo"
stloc.0 // str
ldloc.0 // str
ldloc.0 // str
callvirt String.get_Length ()
ldc.i4.2
sub
callvirt String.Substring (Int32)
stloc.1 // str2
ldloc.1 // str2
call Console.WriteLine (String)
nop
ret

关于C# 8 从字符串中获取最后 n 个字符的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67314292/

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