【问题标题】:create (=compile) class at runtime that implements known interface在运行时创建(=编译)实现已知接口的类
【发布时间】:2013-08-06 14:59:40
【问题描述】:

是否可以通过运行时编译的代码 sn-p 来提供接口的实现?

以下不起作用(安全类型转换返回“null”):

一个完整的控制台应用程序:

using System;
using System.Collections.Generic;

namespace Foo
{
    using System.CodeDom.Compiler;

    using Microsoft.CSharp;

    class Program
    {
        static void Main(string[] args)
        {
            // code snippet to compile:   
            string source =@"namespace Foo {

    public class Test:ITest
    {
        public void Write()
        {
            System.Console.WriteLine(""Hello World"");
        }
    }

    public interface ITest
    {

        void Write();
    }
}
   ";//end snippet

      // the "real" code:

            Dictionary<string, string> providerOptions = new Dictionary<string, string>
                {
                    {"CompilerVersion", "v4.0"}
                };
            CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

            CompilerParameters compilerParams = new CompilerParameters
            {
                GenerateInMemory = true,
                GenerateExecutable = false
            };

            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);

            if (results.Errors.Count == 0)
            {

            }

            ITest test = results.CompiledAssembly.CreateInstance("Foo.Test") as Foo.ITest;

            test.Write(); // will crash here because it is "null"

            Console.ReadLine();
        }
    }

    public interface ITest
    {

        void Write();
    }
}

演员“as ITest”没有成功,即。返回空值。 看来控制台程序中定义的类型“ITest”与编译代码sn-p中定义的类型“ITest”不兼容。

我知道我可以使用反射来调用方法,但是通过接口访问它们当然更舒服。

【问题讨论】:

    标签: c# compilation runtime


    【解决方案1】:

    您有两个不同的ITest 接口,它们恰好看起来相同。
    它们不是同一类型。

    相反,您需要添加对在 CodeDOM 编译器中定义原始接口的程序集的引用。

    【讨论】:

    • 谢谢。所以我只需要添加这一行:compilerParams.ReferencedAssemblies.Add(typeof(Program).Assembly.Location);当然还要去掉代码 sn-p 中的 ITest 接口。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2013-12-19
    • 2012-05-16
    • 1970-01-01
    相关资源
    最近更新 更多