Вопрос

I compile a class using CSharpCodeProvider from string and return the instance of compiled class as dynamic:

CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
CompilerResults compilerResults = compiler.CompileAssemblyFromSource(parms, myClassCode);
Assembly assembly = compilerResults.CompiledAssembly;
resultType = assembly.GetType("MyClass");
var res = resultType.GetConstructor(new Type[] {}).Invoke(new object[] {});
return (dynamic)res;

All compiles without errors and returns instance is what I need, but when I'm trying access some field of it I get an exception:

'object' does not contain a definition for MyInstancePublicField

As I think my mistake is using cast to dynamic type, but there is no any other way I've found to access fields which become known only at runtime.

Это было полезно?

Решение

By default, dynamic will not allow you to use non-accessible members.

Since your type is defined in a different assembly, you need to make the type and the properties public.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top