在实现已知接口的运行时创建(= compile)类 [英] create (=compile) class at runtime that implements known interface

查看:47
本文介绍了在实现已知接口的运行时创建(= compile)类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过在运行时进行编译的代码片段来提供接口的实现?

Is it possible to provide the implementation of an interface by a code snippet that gets compiled at runtime ?

以下内容不起作用(安全类型强制转换返回"null"):

The following does not work (the safe type cast returns "null"):

完整的控制台应用程序:

A complete console application:

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"即失败.返回null.似乎控制台程序中定义的"ITest"类型与已编译的代码片段中定义的"ITest"类型不兼容.

The cast "as ITest" does not succeed ie. return null. It seems that the type "ITest" defined in the console program is not compatible with the type "ITest" defined in the compiled code snippet.

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

I know that I can use Reflection to invoke methods, but of course it's more comfortable to access them via an interface.

推荐答案

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

You have two different ITest interfaces that happen to look the same.
They are not the same type.

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

Instead, you need to add a reference to the assembly that defines the original interface in the CodeDOM compiler.

这篇关于在实现已知接口的运行时创建(= compile)类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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