動的にクラスを作成する必要があります。ほとんどのものは正常に動作しますが、私はコンストラクタを生成することに固執しています。ベースクラスの型と呼び出しコンストラクタを動的に作成
AssemblyBuilder _assemblyBuilder =
AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("MyBuilder"), AssemblyBuilderAccess.Run);
ModuleBuilder _moduleBuilder = _assemblyBuilder.DefineDynamicModule("MyModule");
public static object GetInstance<TSource, TEventArgs>(this TSource source, string eventName)
where TSource : class
{
var typeName = "MyTypeName";
var typeBuilder = _moduleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public);
// create type like class MyClass : GenericType<MyClass, TSource, TEventArgs>
var baseNotGenericType = typeof(GenericType<,,>);
var baseType = baseNotGenericType.MakeGenericType(typeBuilder, typeof(TSource), typeof(TEventArgs));
typeBuilder.SetParent(baseType);
// the base class contains one constructor with string as param
var baseCtor = baseNotGenericType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(string) }, null);
var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard | CallingConventions.HasThis, new Type[0]);
var ilGenerator = ctor.GetILGenerator();
// i want to call the constructor of the baseclass with eventName as param
ilGenerator.Emit(OpCodes.Ldarg_0); // push "this"
ilGenerator.Emit(OpCodes.Ldstr, eventName); // push the param
ilGenerator.Emit(OpCodes.Call, baseCtor);
ilGenerator.Emit(OpCodes.Ret);
var type = typeBuilder.CreateType();
// return ...
}
私はBadImageFormatExceptionを取得しています。何が間違っているのですか?
要求通り:私は、問題があることだと思う
public class MyType : BaseClass<MyType, ConcreteSourceType, ConcreteEventArgsType>
{
protected MyType() : base("SomeName")
{
}
}
は見てくださいここhttp://stackoverflow.com/questions/893423/how-do-create-a-dynamic-class-in-c-sharp-4 –
本当に役に立たなかったか、何か迷ったのですか?私はベースクラスを継承し、引数を持つベースコンストラクタと呼んでいます。 – SACO
このリンクも試してみてくださいhttp://blogs.msdn.com/b/cburrows/archive/2009/04/22/dynamic-base-classes-in-c-4.aspx –