简体   繁体   中英

C# static function with this as parameter to Java function

I got a C# project which needs to be rewritten to java. Unfortunately the original programmer cannot be reached and I have some troubles with some of the C# specific things in the project.

Lets say we have a class in C# like:

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

I dont understand the this before the parameter in this function. What does it reference to? I mean we're in a static class and a static function, so whats "this"? Is it just a reference to t then?

And of course my question would be that this function header is substitute for this in Java:

public static Iterable<MyObject> MyFunc(MyObject t)

Or do I need to do anything else?

Thank you for your help

In this case this refers to any instance of MyObject . It's called 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.

It defines a method which can be used on instances of MyObject class. There is no such thing in Java, so you have to add this method to MyObject class.

Extension methods, like walkhard pointed out in his answer, can be declared anywhere and can simply be called like if they had been declared within the class.

This does not exist in Java. You will have to add MyFunc to the declaration of that Java class.

Using this in that way makes the method an extension method . Java does not have an equivalent. In C#, it is syntactic sugar that lets you do the same thing as this:

MySampleClass.MyFunc(myObject);

With this code:

myObject.MyFunc();

(These compile to the same thing, as long as MySampleClass 's namespace is imported and MyObject doesn't declare its own MyFunc() method.)

Since this doesn't exist in Java, you should simply replace myObject.MyFunc() with MySampleClass.MyFunc(myObject) .

It's an extension method it permit to any object of type MyObject to expose the method MyFunc and use it as a normal instance method (but in reality it's not) it's a normal class method

MyObject o=new MyObject();
//whitout extension method
MyObject.MyFunc(o);
//with extension
o.MyFunc();

It's a syntactic sugar that doesn't exist in java so you have to modify class MyObject and adding instance method MyFunc if you don't want to change all the calls to MyFunc or write a static function and modify every call to MyObject.MyFunc(o);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM