开发者

Extension Method in Dynamically Generated Assembly?

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");
    }
}

}


i think i found out, had to add CompilerVersion to CSharpProvider constructor... var provider = new CSharpCodeProvider( new Dictionary() { { "CompilerVersion", "v3.5" }})

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜