动态生成的程序集中的扩展方法?
我试图在动态生成的程序集中包含扩展方法静态类,但我在第 6 行第 28 列处不断收到“预期类型”编译器错误,该错误恰好位于“this”一词上。如果我删除“this”,则不会返回错误(但它不是扩展方法)。
public static void CodeDomDooDad()
{
using (var provider = new CSharpCodeProvider())
{
var compilerParameters = new CompilerParameters();
compilerParameters.ReferencedAssemblies.Add("system.dll");
compilerParameters.CompilerOptions = "/t:library";
compilerParameters.GenerateInMemory = true;
var sb = new StringBuilder();
sb.Append("namespace MooCow \n{ \n");
sb.Append("public static class Extensions {\n");
sb.Append("public static string ToMoo(this string s) {\n");
sb.Append("return s.Replace(\" \",\"moo\");\n");
sb.Append("}\n");
sb.Append("}\n");
sb.Append("}\n");
//Console.WriteLine(sb.ToString());
var cr = provider.CompileAssemblyFromSource(compilerParameters, sb.ToString());
if (cr.Errors.Count > 0)
{
CompilerError error = cr.Errors[0];
Console.WriteLine(
"error:"+error.ErrorText +
" line:" +error.Line +
" col:" +error.Column +
" isWarning:" + error.IsWarning);
}
}
}
这是生成的代码,运行良好。
namespace MooCow {
public static class Extensions
{
public static string ToMoo(this string s)
{
return s.Replace(" ", "moo");
}
}
}
I'm trying to include an extension methods static class in a dynamically generated assembly, except that i keep getting a compiler error of 'Type expected' at line 6, column 28, which happens to be on the word 'this'. If i remove 'this' no error is returned (but then it is not an extension method).
public static void CodeDomDooDad()
{
using (var provider = new CSharpCodeProvider())
{
var compilerParameters = new CompilerParameters();
compilerParameters.ReferencedAssemblies.Add("system.dll");
compilerParameters.CompilerOptions = "/t:library";
compilerParameters.GenerateInMemory = true;
var sb = new StringBuilder();
sb.Append("namespace MooCow \n{ \n");
sb.Append("public static class Extensions {\n");
sb.Append("public static string ToMoo(this string s) {\n");
sb.Append("return s.Replace(\" \",\"moo\");\n");
sb.Append("}\n");
sb.Append("}\n");
sb.Append("}\n");
//Console.WriteLine(sb.ToString());
var cr = provider.CompileAssemblyFromSource(compilerParameters, sb.ToString());
if (cr.Errors.Count > 0)
{
CompilerError error = cr.Errors[0];
Console.WriteLine(
"error:"+error.ErrorText +
" line:" +error.Line +
" col:" +error.Column +
" isWarning:" + error.IsWarning);
}
}
}
This is the generated code, which works fine.
namespace MooCow {
public static class Extensions
{
public static string ToMoo(this string s)
{
return s.Replace(" ", "moo");
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想我发现了,必须将 CompilerVersion 添加到 CSharpProvider 构造函数... var provider = new CSharpCodeProvider( new Dictionary() { { "CompilerVersion", "v3.5" }})
i think i found out, had to add CompilerVersion to CSharpProvider constructor... var provider = new CSharpCodeProvider( new Dictionary() { { "CompilerVersion", "v3.5" }})