Return (anonymous type with function) from function - is there a better way?

That is why he is known, this question is mostly academic, although I tried to use this concept in the real world. I understand that the example is contrived, but I believe that the concept is valid.

I want to write some free code, for example:

copy(my_first_file).to(my_second_file) 

Short, easy to read and understand, completely legal. Therefore, I define my copy method as follows:

 Private Function copy(FilePath as String) As Object Return New With {.to = New Action(Of String)(Function(x) my_real_copy_method(FilePath,x))} End Function 

I understand that I cannot force an anonymous type to a specific type (for example, implement an interface or some other class), and I do not want the overhead to define a specific class to match my desired free name with the name of the actual method. So I was able to make the code like this:

 copy(my_first_file).to.Invoke(my_second_file) 

So there is no IntelliSense or type, and I have to enable Invoke to run this method. How can I get more type safety and exclude the Invoke method, under these restrictions:

  • Anonymous type returned from method
  • No additional classes or interfaces.
  • Preferably, I do not want to pass another parameter to the copy () method, which tells which type will be returned if the copy does not become a universal method (but I think it means defining a different class / interface, I want to do it)

I know that sounds pretty demanding, feel free to call "Bull" if it's hard for me!

Thanks in advance.

+4
source share
3 answers

Since VB does not have return type output for common methods, even if there is no ambiguity, there is a no way.

You can have a strongly typed function that returns an anonymous type using generics, but you cannot call it with the derived generics, you need to explicitly specify them.

 Private Function Copy(Of T)(filePath as String, prototype As T) As T Return New With { .To = … } End Function 

(.NET adapted naming convention)

This should be called as follows:

 Dim nullAction As Action(Of String) = Nothing Dim proto = New With { .To = nullAction } Copy(firstFile, proto).To(secondFile) 
+3
source

Excuse me; this is the best i could think of. It does not meet your requirements .... but it gives you the syntax you wanted.

 Sub Main() copy("myFile").To("myOtherFile") End Sub Private Function copy(ByVal FilePath As String) As String Return FilePath End Function <Extension()> _ Public Sub [To](ByVal FromFile As String, ByVal ToFile As String) ' Code to really copy goes here my_real_copy_method(FromFile, ToFile) End Sub 
+1
source

I know that you said that your example is contrived, but what about this? It supports a chain of methods ( CopyTo returns a FileInfo ), even if it is not fluent . It is also built into System.IO .

 Dim f As New FileInfo("c:\x.txt") f.CopyTo("c:\y.txt") 
0
source

Source: https://habr.com/ru/post/1342159/


All Articles