C# 如何访问运行时编译类型的字段

C# 如何访问运行时编译类型的字段,c#,dynamic,codedom,C#,Dynamic,Codedom,我使用CSharpCodeProvider从字符串编译一个类,并将编译后的类的实例作为动态返回: CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp"); CompilerResults compilerResults = compiler.CompileAssemblyFromSource(parms, myClassCode); Assembly assembly = compilerResults.Com

我使用CSharpCodeProvider从字符串编译一个类,并将编译后的类的实例作为动态返回:

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;
我需要的是所有无错误的编译和返回实例,但当我尝试访问其中的某个字段时,会出现异常:

“对象”不包含MyInstancePublicField的定义

我认为我的错误是使用“转换为动态类型”,但我发现没有其他方法可以访问只有在运行时才知道的字段。

默认情况下,“动态”将不允许您使用不可访问的成员


由于您的类型是在不同的程序集中定义的,因此您需要将类型和属性公开。

将其公开,或使用反射。MyInstancePublicField是公共字段也将类型公开。这对我很有帮助,谢谢!你可以写它作为答案,以被接受。