问题
I'm creating a class on runtime and some of the types are already created inside the ModuleBuilder and I would like to reused them, but I only have the Type and not the TypeBuilder (Which is what I need in order to change it)
Is there a way to convert from Type to TypeBuilder?
Type moduleType = ModuleBuilder.GetType(inXmlTemplateProperty.PropertyName);
if (moduleType == null)
{
TypeBuilder newClass = ModuleBuilder.DefineType(inXmlTemplateProperty.PropertyName,
TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Serializable);
newClass.SetClassAttributes(inXmlTemplateProperty);
return newClass;
}
return (TypeBuilder)moduleType;
Any suggestion is welcome, thanks in advance.
回答1:
TypeBuilder is a derived type of Type (via intermediate class TypeInfo).
So you can cast a TypeBuilder into a Type. But not the other way around.
You need to use the highest common level of abstraction (Type).
Do not cast moduleType into a TypeBuilder. Later on, you will be able to check if the type has been already created or not, using code like that :
class Program
{
private static Type GetSomeTypePending(string typeName)
{
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("toto.dll"), AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule("toto.dll");
TypeBuilder tb = mb.DefineType(typeName);
return tb;
}
private static Type GetSomeTypeCreated(string typeName)
{
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("toto.dll"), AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule("toto.dll");
TypeBuilder tb = mb.DefineType(typeName);
tb.CreateType(); // do not return the created type,
return tb; // return the typebuilder
}
static void Main(string[] args)
{
Type foo = GetSomeTypePending("tutu");
Type foo2 = GetSomeTypeCreated("tutu");
if (IsPendingTypeBuilder(foo))
{
Console.WriteLine("foo not yet created");
}
else
{
Console.WriteLine("foo created");
}
if (IsPendingTypeBuilder(foo2))
{
Console.WriteLine("foo2 not yet created");
}
else
{
Console.WriteLine("foo2 created");
}
}
private static bool IsPendingTypeBuilder(Type foo)
{
return (foo is TypeBuilder) && !((foo as TypeBuilder).IsCreated());
}
}
回答2:
some of the types are already created inside the ModuleBuilder and I would like to reuse them
You can't. As soon as you call TypeBuilder.CreateType
, the type becomes frozen. Even if you could get access to the TypeBuilder
, you wouldn't be able to modify the type.
来源:https://stackoverflow.com/questions/44675588/convert-from-type-to-typebuilder