Adm*_*and 3 c# code-generation
如何生成参数未知的方法?
我Microsoft.CSharp.dll用来编译c#脚本:
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters compilerParams = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true };
string scriptCode = GetFullCode(); //here i add usings and so on
var results = provider.CompileAssemblyFromSource(compilerParams, scriptCode);
Run Code Online (Sandbox Code Playgroud)
所以,我需要添加一些一些功能,但这种功能可与任意数量的参数和类型(列表DateTime,int,double等).
函数应该像这样调用:
function(String,String,DateTime,int,...);
Run Code Online (Sandbox Code Playgroud)
要么
function(DateTime,int,String,..);
Run Code Online (Sandbox Code Playgroud)
等等.
用户可以在代码中使用此功能.
如何生成这个功能?例如,我告诉我现在如何生成代码:
// GetFullCode:
StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry de in Assembles)
{
foreach (var us in de.Value.ToString().Split(new char[] { ';' }))
{
if (!string.IsNullOrWhiteSpace(us))
sb.AppendLine("using " + us + ";");
}
}
sb.AppendLine("namespace " + Namespace + "\n{");
sb.AppendLine(GetClassCode());
if(withMainFunc)
{
sb.AppendLine(@"static class Program
{
[STAThread]
static void Main()
{
//some init code
}
}");
}
sb.AppendLine("}");
Run Code Online (Sandbox Code Playgroud)
这是一种具有可变参数量的方法
public static string funcion(params object[] Items)
{
StringBuilder sb = new StringBuilder();
foreach (var item in Items)
{
sb.Append(item);
}
return sb.ToString(); ;
}
Run Code Online (Sandbox Code Playgroud)
这会将所有给定值添加到一个字符串中.
用途: string Result = funcion(DateTime.Now, "foo", 1);