尝试在动态创建的程序集上绑定动态方法会导致RuntimeBinderException

MgS*_*Sam 9 .net c# reflection dynamic-language-runtime dynamic

我有一个方便的实用程序方法,它接受代码并吐出内存中的程序集.(它使用CSharpCodeProvider,虽然我不认为这应该重要.)这个程序集像任何其他反射一样工作,但当与dynamic关键字一起使用时,似乎失败了RuntimeBinderException:

'object'不包含'Sound'的定义

例:

var assembly = createAssembly("class Dog { public string Sound() { return \"woof\"; } }");
var type = assembly.GetType("Dog");
Object dog = Activator.CreateInstance(type);

var method = type.GetMethod("Sound");
var test1Result = method.Invoke(dog, null); //This returns "woof", as you'd expect

dynamic dog2 = dog;
String test2Result = dog2.Sound(); //This throws a RuntimeBinderException
Run Code Online (Sandbox Code Playgroud)

有谁知道DLR无法处理这个问题的原因?有什么办法可以解决这个问题吗?

编辑:

createAssembly方法:

免责声明:其中一些内容包含扩展方法,自定义类型等.但它应该是不言自明的.

private Assembly createAssembly(String source, IEnumerable<String> assembliesToReference = null)
{
    //Create compiler
    var codeProvider = new CSharpCodeProvider();

    //Set compiler parameters
    var compilerParameters = new CompilerParameters
    {
        GenerateInMemory = true,
        GenerateExecutable = false,
        CompilerOptions = "/optimize",
    };

    //Get the name of the current assembly and everything it references
    if (assembliesToReference == null)
    {
        var executingAssembly = Assembly.GetExecutingAssembly();
        assembliesToReference = executingAssembly
            .AsEnumerable()
            .Concat(
                executingAssembly
                    .GetReferencedAssemblies()
                    .Select(a => Assembly.Load(a))
            )
            .Select(a => a.Location);
     }//End if

    compilerParameters.ReferencedAssemblies.AddRange(assembliesToReference.ToArray());

    //Compile code
    var compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, source);

    //Throw errors
    if (compilerResults.Errors.Count != 0)
    {                
        throw new CompilationException(compilerResults.Errors);                
    }

    return compilerResults.CompiledAssembly;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*vey 5

上课public.

var assembly = createAssembly("public class Dog { public string Sound() ...
                               ^
Run Code Online (Sandbox Code Playgroud)

这解决了我的机器上的问题.