Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using emitted type as type parameter in Reflection.Emit

[Name("Admin")]
public class TestAdmin : TestUserBase<TestAdmin>
{
    public TestAdmin(Type webDriverType) : base(webDriverType)
    {
    }
}

Currently, I have a bunch of classes of this form that I'd like to create at runtime using Reflection.Emit. However, I'm running into an issue when I attempt to add the parent - since the TestAdmin class doesn't exist before runtime, I don't know how to create

TestUserBase<TestAdmin>

Any ideas?

like image 589
Matt Koster Avatar asked Jun 10 '13 21:06

Matt Koster


2 Answers

You can set the parent type using SetParent:

TypeBuilder tb = mb.DefineType("TestAdmin", TypeAttributes.Public);
tb.SetParent(typeof(TestUserBase<>).MakeGenericType(tb));

Type theType = tb.CreateType();
like image 197
Lee Avatar answered Sep 23 '22 16:09

Lee


OK. I haven't been able to test this thoroughly, but I think this is possible. Try something like this:

Assuming your generic base class is already defined (i.e., you're not generating TestUserBase<T>), you should be able to do something like this:

var emittedType = module.DefineType("TestAdmin", TypeAttributes.Public | TypeAttributes.Class);
var baseType = typeof(TestUserBase<>).MakeGenericType(type);
emittedType.SetParent(baseType);

Of course, if TestUserBase<T> is begin generated, you can use this same logic using MakeGenericType on the dynamic type TestUserBase<T>. The SetParent logic is the same.

like image 36
Michael Gunter Avatar answered Sep 19 '22 16:09

Michael Gunter