Skip to main content
 首页 » 编程设计

c#之Mono.CSharp(编译器即服务)在 2.10 版中的变化

2024年02月23日15langtianya

我在 Ubuntu 11.10 上运行 Mono 版本 2.10。我正在尝试运行 http://blog.davidebbo.com/2012/02/quick-fun-with-monos-csharp-compiler-as.html 上提供的示例,但它似乎针对不同版本的单声道。例如 Compile 是 Evaluator 上的静态方法。我对他的示例进行了以下更改,但没有成功。任何人都可以提供正确的更改,并且有人知道是否有任何关于 Mono.CSharp 的 API 更改的信息?我的编译器报出的版本如下:

$ dmcs --version 
Mono C# compiler version 2.10.5.0 

我使用此命令行编译了以下代码:

dmcs -r:Mono.CSharp 示例.cs

并在编译时收到此警告。

dmcs -r:Mono.CSharp Sample.cs 
Sample.cs(26,17): warning CS0219: The variable `compiledMethod' is assigned but its value is never used 
Compilation succeeded - 1 warning(s) 

这是运行代码的结果:

$ ./Sample.exe  
{interactive}(2,40): error CS1525: Unexpected symbol `namespace', expecting `end-of-file' or `using' 
{interactive}(4,70): error CS0101: The namespace `UserCode' already contains a definition for `Foo' 
{interactive}(4,70): (Location of the symbol related to previous error) 

这是我目前的代码:

using System; 
using System.IO; 
using Mono.CSharp; 
using System.Reflection; 
 
namespace Sample 
{ 
    public interface IFoo { string Bar(string s); } 
 
    class Program 
    { 
        const string code = @" 
            using System; 
            namespace UserCode 
            { 
                public class Foo : Sample.IFoo 
                { 
                    public string Bar(string s) { return s.ToUpper(); } 
                } 
            } 
        "; 
 
        static void Main(string[] args) 
        { 
            Mono.CSharp.Evaluator.Init(new string[] {} ); 
            Evaluator.ReferenceAssembly(Assembly.GetExecutingAssembly()); 
 
            var compiledMethod = Evaluator.Compile(code); 
 
            for (;;) 
            { 
                string line = Console.ReadLine(); 
                if (line == null) break; 
 
                object result; 
                bool result_set; 
                Evaluator.Evaluate(line, out result, out result_set); 
                if (result_set) Console.WriteLine(result); 
            } 
        } 
    } 
} 

请您参考如下方法:

Mono 2.10 附带的 Evaluator 仅支持表达式和语句。您的代码包含 Mono 2.10 不支持的类型声明。

Mono 2.11 或 git master Mono.CSharp 支持类型声明和其他高级功能。