I've been trying to write a function that takes in a string, and turns it into invokable delegate for an class instance.
The problem that occurs is that i get an exception that states that the instanced class and the class of the methodinfo hta im using, are not the same.
My code is in no way correct, as i am currently learning about this part of the C# language, so if anyone could provide som code that performes the afformentiond task, that would be great.
Just to give you an idea of what im talking about, im gonna show you my attempt.
public class GameObject
{
public int x { get; private set; }
public Transform transform { get; private set; }
public RenderObject2d renderObject { get; private set; }
public PhysicsObject2d physicsObject { get; private set; }
public GameObject()
{
x = new int();
transform = new Transform(Engine.w/2, Engine.h/2, 0, 0);
renderObject = new RenderObject2d(transform);
physicsObject = new PhysicsObject2d(transform);
}
public void CreateUpdate()
{
MethodInfo method;
string temp = @"
namespace GameEngine
{
class Player
{
public void Update()
{
}
}
}
";
Assembly assembly = Assembly.GetExecutingAssembly();
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.ReferencedAssemblies.Add("GameEngine.exe");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, temp);
if (results.Errors.HasErrors)
{
StringBuilder sb = new StringBuilder();
foreach (CompilerError error in results.Errors)
{
sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
}
throw new InvalidOperationException(sb.ToString());
}
Type type = results.CompiledAssembly.GetType("GameEngine.Player");
method = type.GetMethod("Update");
method.Invoke(this, null);
}
}
Aucun commentaire:
Enregistrer un commentaire