jeudi 2 août 2018

How to Apply XmlIncludeAttribute to TypeBuilder?

I am developing a library in C# that generates runtime types using System.Reflection.Emit.TypeBuilder class and i want to generate the following class hierarchy:

[XmlInclude(typeof(Derived))]
public class Base
{
}

public class Derived : Base
{
}

var baseTypeBuilder = moduleBuilder.DefineType("Base", TypeAttributes.Public, typeof(Base));

var derivedTypeBuilder = moduleBuilder.DefineType("Derived", TypeAttributes.Public, typeof(Derived));

derivedTypeBuilder.SetParent(baseTypeBuilder);

baseTypeBuilder.SetCustomAttribute(new CustomAttributeBuilder(typeof(XmlIncludeAttribute).GetConstructor(new[] { typeof(Type) }), new[] { derivedTypeBuilder }));

var baseType = baseTypeBuilder.CreateType();

var derivedType = derivedTypeBuilder.CreateType();

Now, when i call:

var attribute = baseType.GetCustomAttribute<XmlIncludeAttribute>();

I receive the following error:

Could not load file or assembly 'Test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

Any ideas are well-appreciated: how can i apply a custom attribute on a TypeBuilder for base class that refers to a TypeBuilder for a derived class?





Aucun commentaire:

Enregistrer un commentaire