gpt4 book ai didi

以 this 作为 Java 函数参数的 C# 静态函数

转载 作者:行者123 更新时间:2023-11-29 05:43:11 24 4
gpt4 key购买 nike

我有一个 C# 项目需要重写为 java。不幸的是,无法联系到最初的程序员,我在项目中遇到了一些 C# 特定问题。

假设我们在 C# 中有一个类:

public static class MySampleClass : Object
{
...
public static IEnumerable<MyObject> MyFunc(this MyObject t) {
//a lot of code
}
...
}

我不明白这个函数中参数前的this。它指的是什么?我的意思是我们在一个静态类和一个静态函数中,那么“this”是什么?那么它只是对 t 的引用吗?

当然我的问题是这个函数头在 Java 中替代了这个:

public static Iterable<MyObject> MyFunc(MyObject t)

或者我还需要做其他事情吗?

谢谢你的帮助

最佳答案

在这种情况下,this 指的是 MyObject 的任何实例。它叫做extension method :

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

它定义了一个可以在 MyObject 类的实例上使用的方法。 Java中没有这样的东西,所以你必须把这个方法添加到MyObject类中。

关于以 this 作为 Java 函数参数的 C# 静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16817936/

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