D 中的扩展方法?
嘿伙计们,我正在尝试让这些语法对我来说有意义:
S[] split(S)(S s) if (isSomeString!S)
{
...
}
并且
string join(in string[] words, string sep)
{
...
}
(如 phobos/src/std/string.d
中所示)
据我所知,这是这段代码让我们可以做这样的事情:
string[] parts = "/foo/bar/baz".split("/"); // string[] {"foo", "bar", "baz"}
string part = parts.join("-"); // string "foo-bar-baz"
这基本上让我相信像我从 CSharp 知道的扩展方法这样的东西在 d 中是可能的。我遇到的问题是:
- 我不能 100% 确定我在这里查看的是正确的函数声明
- 我不明白是什么让它们相似。
Hey folks, I'm trying to get these bits of syntax to make sense to me:
S[] split(S)(S s) if (isSomeString!S)
{
...
}
and
string join(in string[] words, string sep)
{
...
}
(As seen in phobos/src/std/string.d
)
As far as I can tell, this is the piece of code that lets us do stuff like:
string[] parts = "/foo/bar/baz".split("/"); // string[] {"foo", "bar", "baz"}
string part = parts.join("-"); // string "foo-bar-baz"
Which basically makes me believe something like the extension methods I know from CSharp are possible in d. The problems I have are:
- That I'm not 100% sure i'm looking at the right function declarations here
- That I don't see what makes them similar.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们本身并不是扩展方法,只是一些变成了一个简洁功能的错误。
这两种方法的相似之处在于,它们都将字符串作为第一个参数。所以这里起作用的技巧是,给定一个数组 T[] arr,并且
可以通过执行以下操作来调用函数
They're not extension methods per-se, just some bug that turned into a neat feature.
The similarity between those two methods is that both has a string as the first parameter. So the trick that is at work here, is that given an array T[] arr, and a function
can be called by doing
在 D 中,任何采用数组作为第一个参数的函数都可以像该数组的成员函数一样被调用。由于字符串是数组,因此将包含字符串。因此,类似的东西
可以用两种不同的方式调用:
此功能目前仅适用于数组(IIRC,它的出现是由于允许它的错误,并且我们认为拥有它实际上很好,所以它实际上被制作为语言的一部分),但据推测,在某些时候,它将适用于所有类型。使其适用于所有类型称为统一函数调用语法。实现后,您就可以执行类似的操作
,但由于尚未实现统一的函数调用语法,因此您只能使用数组执行此类操作。人们使用字符串进行编程而不是将它们作为函数的第一个参数传递是很常见的。
In D, any function which takes an array as its first argument can be called as if it were a member function of that array. And since strings are arrays, that would include strings. So, something like
can be called two different ways:
This feature currently only works for arrays (IIRC, it came about due to a bug that allowed it, and it was decided that it was actually nice to have, so it was actually made a part of the language), but supposedly, at some point, it will be made to work for all types. Having it work for all types is called uniform function call syntax. With that implemented, you'd be able to do stuff like
But as uniform function call syntax has not been implemented yet, you can only do that sort of thing with arrays. It's quite common for people to program that way with strings rather than passing them as the first argument to a function.