在C#中添加对动态文件加载器的支持 [英] Adding support for dynamic file loaders in c#

查看:68
本文介绍了在C#中添加对动态文件加载器的支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个使用C#的控制台应用程序,该应用程序可以读取某种格式的文件并将其转换为业务对象,那么我将通过具有IReader接口来设计它,以便我可以支持不同的格式,例如XML,CSV,管道分隔符等,并且每种文件格式都有不同的具体类.

If I have a Console App in C# that reads in files of a certain format and converts them to business objects, I design this by having an IReader interface so that I can support different formats, eg XML, CSV, pipe delimited etc, and have different concrete classes for each file format.

如果要求是能够动态加载新的文件阅读器(新格式)而不必重新编译,那么我有办法吗?

If the requirement is to be able to load new file readers (new formats) in dynamically without having to recompile, is there a way I can accomplish that?

我能想到的唯一方法是以某种方式使用XSD或reg表达式,但在我看来应该有一个更好的解决方案

The only way I can think of is somehow using XSD or reg expressions but it seems to me there should be a better solution

推荐答案

取决于读者的共谋性,您可以决定使用CodeDom让某人直接编写代码.简短示例:

Depends on the complicity of Readers, you may decide to use CodeDom to let someone to write the code directly. Short example:

            // create compiler
            CodeDomProvider provider = CSharpCodeProvider.CreateProvider("C#");
            CompilerParameters options = new CompilerParameters();
            // add more references if needed
            options.ReferencedAssemblies.Add("system.dll");
            options.GenerateExecutable = false;
            options.GenerateInMemory = true;
            // compile the code
            string source = "using System;namespace Bla {public class Blabla { public static bool Test { return false; }}}";
            CompilerResults result = provider.CompileAssemblyFromSource(options, source);
            if (!result.Errors.HasErrors)
            {
                Assembly assembly = result.CompiledAssembly;
                // instance can be saved and then reused whenever you need to run the code
                var instance = assembly.CreateInstance("Bla.Blabla");
                // running some method
                MethodInfo method = instance.GetType().GetMethod("Test"));
                var result = (bool)method.Invoke(_formulas, new object[] {});
            }

但是您可能必须提供某种编辑器或部分完成任务(因此只需编写必要的代码).

But probably you'll have to provide sort of editor or accomplish the task partially (so only necessary code have to be written).

这篇关于在C#中添加对动态文件加载器的支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆