Reputation: 12927
I would like to use the same code for copying files to an FTP server, and through USB. I've already written some code, which as of now uses functions from the System.IO
namespace.
To minimize code duplication, I've listed the functions which I need from the system.IO namespace, and I was thinking of designing an interface exposing similar functions, and then two classes, one for FTP file operations, and one for local ones.
I have a few questions about Interfaces though:
File.*
and Directory.*
organisation be preserved (so that routines declared in the interface follow the same hierarchy than in the IO namespace)?Sub IO.File.Delete Implements IOInterface.File_Delete
)?Dim IOHandler As IOInterface
, assuming that IOInterface
is the name of my interface? Can I then write both IOHandler = New LocalIOHandler
and IOHandler = New FTPIOHandler
, assuming LocalIOHandler
and FTPIOHandler
are my two classes implementing the IOInterface
?Thanks!
CFP.
Upvotes: 0
Views: 137
Reputation: 21742
I can't help you with the first one i simply don't get what you mean with function hierachi but for the other two. No there's no syntax for that you'll have to implement a method that forwards the Call to the method. E.g. (pseudo cod I haven't written VB for years)
Sub open(path as string)
Begin
Return File.Open path
End
For your 3rd you could say that that's the point (it's not the only point) of interfaces that the consuming code does not need to know the concrete type
Upvotes: 1
Reputation: 36310
You can't change an existing class so that it implements your own interface. You can however design your own interface where your methods return classes that already exist - like the ones in the System.IO namespace.
You can also implement your own class that wraps the System.IO classes so that your IOInterface.Delete maps to a FileInfo.Delete (please forgive the C# syntax, my VB is rusty):
public class MyFileClass : IOInterface
{
public void DeleteFile(string fileName)
{
new FileInfo(fileName).Delete();
}
}
In response to #3: Yes. A variable of type IOInterface can hold any type that implements that interface. You can also later cast it to the specific type if you need to.
Upvotes: 1