Theo dõi trên excellent answer này, tôi tự hỏi liệu DLR có sử dụng từ khóa dynamic
có thể cho phép cách viết mã ít hơn đối với cụm được tạo ra không.Sử dụng DLR để chạy mã được tạo bằng CompileAssemblyFromSource?
Ví dụ, có thể mã câu trả lời nói trên của:
using (Microsoft.CSharp.CSharpCodeProvider foo =
new Microsoft.CSharp.CSharpCodeProvider())
{
var res = foo.CompileAssemblyFromSource(
new System.CodeDom.Compiler.CompilerParameters() {
GenerateInMemory = true
},
"public class FooClass { public string Execute() { return \"output!\";}}"
);
var type = res.CompiledAssembly.GetType("FooClass");
var obj = Activator.CreateInstance(type);
var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
}
trở thành một cái gì đó như:
using (Microsoft.CSharp.CSharpCodeProvider foo =
new Microsoft.CSharp.CSharpCodeProvider())
{
var res = foo.CompileAssemblyFromSource(
new System.CodeDom.Compiler.CompilerParameters() {
GenerateInMemory = true
},
"public class FooClass { public string Execute() { return \"output!\";}}"
);
var type = res.CompiledAssembly.GetType("FooClass");
dynamic obj = Activator.CreateDynamicInstance(type);
var output = obj.Execute();
}
Có, có ít mã hơn một chút. Làm cho nó hoạt động bằng cách sử dụng 'Activator.CreateInstance()' thay thế. Tôi không thấy câu hỏi nào khác. –
Có, tôi đã thử nó và nhận ra rằng nó "chỉ hoạt động" với 'dynamic' thay vì' var'. Những thứ tuyệt vời. –