繁体   English   中英

在运行时创建(= compile)类,以实现已知接口

[英]create (=compile) class at runtime that implements known interface

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

以下内容不起作用(安全类型强制转换返回“ 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”即失败。 返回null。 似乎在控制台程序中定义的“ ITest”类型与在已编译的代码片段中定义的“ ITest”类型不兼容。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM