Domanda

We've added a feature for our users to write C# scripts for the application to execute, which are compiled and run at runtime. The scripts may access an API we've exposed, and they're compiled/run by CSharpCodeProvider.

I find that the code compiled at runtime has problems when calling a method with optional arguments, e.g.:

public void BlackmailColonelMustard(int amount, string myAlias, bool tellHisWifeAnyway = true)

If the compiled-at-runtime script calls BlackmailColonelMustard(10000, "Mr Boddy"), the compiler complains that there's no overloaded method with only two arguments, rather than recognize the third parameter's default value.

Naturally it works fine when called from pre-compiled code. Anyone know what I'm doing wrong?

Is it because VS2010 (even pre-.NET 4) is smart enough to compile code which uses optional parameters, but the .NET 3.5 runtime hasn't yet learned that trick?

È stato utile?

Soluzione

Optional arguments have been introduced in C# 4.0. Set compiler version to 4.0 if possible:

Dictionary<string, string> options = new Dictionary<string, string>();
options.Add("CompilerVersion", "v4.0");
CSharpCodeProvider provider = new CSharpCodeProvider(options);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top