开发者

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:

  1. Could design my interface so that the File.* and Directory.* organisation be preserved (so that routines declared in the interface follow the same hierarchy than in the IO namespace)?
  2. 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)?
  3. Can I declare something like 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开发者_如何学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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜