简体   繁体   English

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

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

Is it possible to provide the implementation of an interface by a code snippet that gets compiled at runtime ? 是否可以通过在运行时进行编译的代码片段来提供接口的实现?

The following does not work (the safe type cast returns "null"): 以下内容不起作用(安全类型强制转换返回“ 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();
    }
}

The cast "as ITest" does not succeed ie. 强制转换为“ as ITest”即失败。 return null. 返回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. 似乎在控制台程序中定义的“ ITest”类型与在已编译的代码片段中定义的“ ITest”类型不兼容。

I know that I can use Reflection to invoke methods, but of course it's more comfortable to access them via an interface. 我知道我可以使用Reflection来调用方法,但是通过接口访问它们当然更舒服。

You have two different ITest interfaces that happen to look the same. 您有两个不同的ITest接口,它们看起来相同。
They are not the same type. 它们不是同一类型。

Instead, you need to add a reference to the assembly that defines the original interface in the CodeDOM compiler. 相反,您需要添加对程序集的引用,该引用定义了CodeDOM编译器中的原始接口。

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

相关问题 C#:有没有一种方法可以将类强制转换为在运行时实现的接口,而不是在编译时实现的接口? - C#: Is there a way to cast a class to an interface it implements at runtime, but not compile time? 在运行时创建类型,继承抽象类并实现接口 - Create type at runtime that inherits an abstract class and implements an interface 创建实现接口的匿名类 - Create anonymous class that implements an interface 向实现已知接口的未知类的特定实例添加扩展方法 - Add extension methods to specific instantiations of unknown class that implements a known interface 从它实现的接口创建 class 的实例 - Create Instance of a class from interface which it implements 如何动态加载DLL并在其中使用类(实现已知接口)[C#] - How to dynamically load a DLL and use a class in it (that implements a known interface) [C#] 使用反射创建实现T类型接口的类 - Using reflection to create a class that implements an interface of type T 如何创建从实现接口的基类派生的实例列表? - How to create list of instances deriving from a base class that implements interface? 我如何从运行时已知的类派生一个类,实现编译时已知的接口 - How can I have a class derived from a class known at runtime implementing an interface known at compilation 实现接口的通用基类 - generic base class that implements interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM