[英]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.