I am working with the following class:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
And I have a string containing following:
class PersonActions
{
public static void Greet(Person p)
{
string test = p.Name;
}
}
In my client application developped in WPF (.NET 4.7) I am compiling this string at runtime and invoke the Greet method like this:
Person x = new Person();
x.Name = "Albert";
x.Age = 76;
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
//parameter being an assembly containing the Person class
//code being the code from abrom above (PersonActions)
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
Assembly importassembly = results.CompiledAssembly;
Type assemblytype = importassembly.GetType("PersonActions");
ConstructorInfo constructor = assemblytype.GetConstructor(Type.EmptyTypes);
object classObject = constructor.Invoke(new object[] { });
MethodInfo main = assemblytype.GetMethod("Greet");
main.Invoke(classObject, new object[] { x });
Unfotunately this always crashes because somehow it cannot find the method with the same parameter type even if the types come from the same assembly. Somehow it is just looking for: public static void Greet(object p)
Using just 'object' as parameter type works, but is not a possibility in my case.
Is there a way to recieve the object in the type that it is? Or maby to tell the Invocation method that the types match?
Aucun commentaire:
Enregistrer un commentaire