Interfaces in .Net
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:
- Could design my interface so that the
File.*
andDirectory.*
organisation be preserved (so that routines declared in the interface follow the same hierarchy than in the IO namespace)? - Is there a way, for local operations, to just map functions from the IO namespace to the corresponding interface functions (writing something like
Sub IO.File.Delete Implements IOInterface.File_Delete
)? - Can I declare something like
Dim IOHandler As IOInterface
, assuming thatIOInterface
is the name of my interface? Can I then write bothIOHandler = New LocalIOHandler
andIOHandler = New FTPIOHandler
, assumingLocalIOHandler
andFTPIOHandler
are my two classes implementing theIOInterface
?
Thanks!
CFP开发者_如何学Go.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.
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
精彩评论