Sorry I'm new at programming using CodeDom, I have this problem that I couldn't solve. Was thinking if some of you folks know the solution.
I have the following code inside a class file:
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;
}
I would like to input the data (a custom created class, that has an array of another custom class inside) variable as the parameter in the DoStuff function, I keep on having errors. Is there a way to solve this issue?
Multiple errors, change this way:
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 });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.