C#CodeDom:自定义类作为字符串代码中的参数

本文关键字:代码 参数 字符串 自定义 C#CodeDom | 更新日期: 2023-09-27 18:22:24

很抱歉,我是使用CodeDom编程的新手,我有这个问题无法解决。我在想你们中的一些人是否知道解决方案。

我在一个类文件中有以下代码:

public class AnotherCustomClass {
    public string Employer { get; set; }
    public DateTime? DateOfHire { get; set; }
}
public class CustomClass {
    public int X { get; set; }
    public int Y { get; set; }
    public AnotherCustomClass[] YetAnother { get; set; }
}
public void DoSomething()
{
    string expression = @"using System;  
    namespace MyNamespace {
        public class MyClass {
            public static int DoStuff(CustomClass myCustomClass) {
                return myCustomClass.X + myCustomClass.Y;
            }
        }
    }";
    CSharpCodeProvider provider = new CSharpCodeProvider();
    CompilerParameters assemblies = new CompilerParameters(new[] { "System.Core.dll" });
    CompilerResults results = provider.CompileAssemblyFromSource(assemblies, expression);
    Type temporaryClass = results.CompiledAssembly.GetType("MyNamespace.MyClass");
    MethodInfo temporaryFunction = temporaryClass.GetMethod("DoStuff");
    CustomClass data = new CustomClass() { X = 1, Y = 2 };
    object result = temporaryFunction.Invoke(null, new object[] { data });
    return result;
}

我想输入data(一个自定义创建的类,里面有另一个自定义类的数组)变量作为DoStuff函数中的参数,我一直有错误。有办法解决这个问题吗?

C#CodeDom:自定义类作为字符串代码中的参数

多个错误,更改方式:

string expression = @"using System;  
namespace MyNamespace {
    public class MyClass {
        public static int DoStuff(CustomClass myCustomClass) {
            return myCustomClass.X + myCustomClass.Y;
        }
    }
    public class CustomClass
    {
        public int X;
        public int Y;
        public CustomClass(int x, int y) { X = x; Y = y; }
    }
}";
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters assemblies = new CompilerParameters(new string[] { "System.dll" });
CompilerResults results = provider.CompileAssemblyFromSource(assemblies, expression);
Type temporaryClass = results.CompiledAssembly.GetType("MyNamespace.MyClass");
Type parClass = results.CompiledAssembly.GetType("MyNamespace.CustomClass");
MethodInfo temporaryFunction = temporaryClass.GetMethod("DoStuff");
object mc = parClass.GetConstructor(new Type[] { typeof(int), typeof(int) }).Invoke(new object[]{1,2});
object result = temporaryFunction.Invoke(null, new object[] { mc });