mardi 7 août 2018

C# Create a runtime class that inherits an interface, and overrides the methods

This might be a little unusual but all of this is to avoid code generation.

My goal: To create a dynamic class that inherits an Interface and I also want to override all public methods.

What I've got so far:

public class Program
{
    private static void Main(string[] args)
    {
        var bmw = new BMW();
        var maker = bmw.Vehicle.Maker();
        Console.WriteLine(maker);
    }
}

public class BMW : SmartCar<ICar>
{
    public BMW() : base()
    {
    }
}

public class SmartCar<T> where T : class
{
    public T Vehicle { get; set; }

    public SmartCar()
    {
        Vehicle = Activator.CreateInstance(MyTypeBuilder.CompileResultType(typeof(T))) as T;
    }
}

public interface ICar
{
    string Maker();
}

For reference the MyTypeBuilder comes from : How to dynamically create a class in C#?

And I've made a few changes:

private static void CreateMethod(MethodInfo t, TypeBuilder tb)
    {
        // MethodBuilder
        var mbuilder = tb.DefineMethod(t.Name,
            MethodAttributes.Public, // | MethodAttributes.Static, // Only works if Static is there
            t.ReturnType,
            t.GetParameters().Select(x => x.ParameterType).ToArray());

        Expression<Func<string>> expression = () => "Hi BMW";

        expression.CompileToMethod(mbuilder);
    }

If I don't put the static I get a invalid argument value. Otherwise with the static method attribute I get want I want:

DynamicType

The problem is when I try to cast it:

Vehicle = Activator.CreateInstance(MyTypeBuilder.CompileResultType(typeof(T))) as T;

Gives me a null, so to try to fight this issue, I've added in the CompileResultType a "AddInterfaceImplementation" to my dynamic class, because I have the Maker() method implemented!

But this happens: Crash

Does anyone know a way to get around this problem?





Aucun commentaire:

Enregistrer un commentaire