用户给定一种文件,我们要通过一个类来读取,但是读取的结果形式都是已知的,可以被程序使用。我们像把读取功能单独做成模块,如果将来建立新的文件形式,我们只需要增加一个模块就可以了。不知道这种目的在C#里怎样实现?

解决方案 »

  1.   

    使用类厂:
    public interface IReader
    {
         DataResult Read();
    }
    public class ClassFactory
    {
         IReader QueryInterface(string FileType)
         {
               switch(FileType)
               {
                     "excel":
                          return new ExcelReader();
                     "xml":
                          return new XMLReader();
                    ....
               }
         }
    }public class ExcelReader: IReader
    {
         public DataResult Read()
         {
            //读取excel文件的数据
         }
    }public class XMLReader: IReader
    {
         public DataResult Read()
         {
            //读取XML文件的数据
         }
    }
      

  2.   

    真的非常感谢
    ExcelReader、 XMLReader可以做成类库的形式但是     IReader QueryInterface(string FileType)
         {
               switch(FileType)
               {
                     "excel":
                          return new ExcelReader();
                     "xml":
                          return new XMLReader();
                    ....
               }
         }
    还是在程序里定义好的。可不可以像插件那样扩展?
      

  3.   

    是的用反射加载
    你还需要维护一个 文件类型和每个类库之间的对应关系
    类似这样:文件类型        类库
    "excel"  "ExcelReader"
    "xml"    "XMLReader"
    "txt"    "TxtReader"
    .....然后在类厂中根据文件类型(参数), 使用反射加载对应的类库,创建IReader
      

  4.   

    [code=C# public class ClassFactory
    {
    //ArrayList m_Plugin; static public IDPlugin.IPlugin GetInterface(string FileName,string Plugin)
    {
    Assembly dll;
    dll = System.Reflection.Assembly.LoadFile(FileName);
    Type t;
    Plugin = "IDPlugin."+Plugin;
                t = dll.GetType(Plugin);
    if(t==null) throw new Exception( "There is not "+Plugin); if(t.GetInterface("IDPlugin.IPlugin")!=null)        return (IDPlugin.IPlugin)Activator.CreateInstance(t);
    else
    return null; } }][/code]