C# - 加载文本文件作为一类 [英] C# - Load a text file as a class

查看:166
本文介绍了C# - 加载文本文件作为一类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法来加载.txt文件为一类,其中我的主要程序然后调用函数?基本上,我试图mod支持添加到我的简单的应用程序,用户可以选择每个文件的选项。该文件遵循了类似的(但不相同)的格式,带着一帮空隙(函数)被调用的主程序。

Is there any way to load a .txt file as a class, which my main program can then call functions from? I'm basically trying to add mod support to my simple app, where the user can select options from each file. The file follows a similar (but not the same) format, with a bunch of voids (functions) that are called in the main program.

我怎样才能做到这一点?是,甚至有可能做的(可能不是,回答我的问题?),认为它不会与程序的其他部分一起被编?

How can I do this? Is that even possible to do (probably not, answering my own question?), considering it wouldn't be compiled along with the rest of the program?

谢谢!

推荐答案

请参阅我来回答这个问题:的在运行时编译C#阵列,并在代码中使用它?

See me answer to this question: Compile a C# Array at runtime and use it in code?

从本质上讲,你想拉你的文本文件到的CodeDOM和编译。在此之后,它可能会有所帮助创建一些动态方法为执行帮手。

Essentially, you would want to pull your text file into the CodeDom and compile it. After that, it would likely be helpful to create a few dynamic methods as execution helpers.


  • 接收上传文件

  • 在文件

  • 执行任何所需的验证读取文件作为串入的CodeDOM

  • 与任何编译器/结构错误应对<使用LINQ表达式树或动态方法/ LI>
  • 创建辅助方法,使新的类和现有的代码之间的连接是用编译对象(否则桥接,所有的新的方法将需要使用被调用反射)

  • Receive uploaded file
  • Perform any needed validation on the file
  • Read the file as a string into the CodeDom
  • Deal with any compiler/structure errors
  • Create helper methods using Linq expression trees or dynamic methods so that the linkage between the new class and existing code is bridged with a compiled object (otherwise, all the new methods would need to be invoked using reflection)
var csc = new CSharpCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } } );
var cp = new CompilerParameters() {
    GenerateExecutable = false,
    OutputAssembly = outputAssemblyName,
    GenerateInMemory = true
};

cp.ReferencedAssemblies.Add( "mscorlib.dll" );
cp.ReferencedAssemblies.Add( "System.dll" );

StringBuilder sb = new StringBuilder();

// The string can contain any valid c# code

sb.Append( "namespace Foo{" );
sb.Append( "using System;" );
sb.Append( "public static class MyClass{");
sb.Append( "}}" );

// "results" will usually contain very detailed error messages
var results = csc.CompileAssemblyFromSource( cp, sb.ToString() );






另外,请参阅本主题:Implementing在C#的脚本语言。 IronPython的与DLR 的可能适合您的需求。


Also, see this topic: Implementing a scripting language in C#. IronPython with the DLR might be suitable for your needs.

这篇关于C# - 加载文本文件作为一类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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