Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create a c# generic type with self referenced constraints

I have a generic type that look like this

public class Entity<T> where T : Entity<T>{ ... }

and I need to dynamically construct the type T. So that it looks like this:

public class MyClass : Entity<MyClass>{ ... }

Can this be done ?

like image 272
Rushui Guan Avatar asked Apr 04 '12 23:04

Rushui Guan


People also ask

What is a dynamic object C#?

Dynamic objects expose members such as properties and methods at run time, instead of at compile time. This enables you to create objects to work with structures that do not match a static type or format.

How do you create a dynamic class?

Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object. print ( type ( "Geeks4Geeks !" ))

How do you make an object dynamic?

To create a dynamic object, you simply need to specify the objectClass to have a value of dynamicObject in addition to its structural objectClass (e.g., user ) value when instantiating the object. The entryTTL attribute can also be set to the number of seconds before the object is automatically deleted.

Can we create a class at runtime?

Dynamic Class creation enables you to create a Java class on the fly at runtime, from source code created from a string. Dynamic class creation can be used in extremely low latency applications to improve performance.


1 Answers

AssemblyName assemblyName = new AssemblyName("TestAssembly");
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);

ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

TypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Public);

Type entityType = typeof(Entity<>).MakeGenericType(typeBuilder);

typeBuilder.SetParent(entityType);


Type t = typeBuilder.CreateType();
like image 157
Joe Enzminger Avatar answered Oct 15 '22 18:10

Joe Enzminger