我想要做的是将静态类的所有静态字段值保存在具有非静态字段的动态创建的非静态类中。
类的创建工作,我可以从类DynamicObject
外部访问字段,但在我的构造函数中,这不起作用。字段的初始化不起作用。循环被跳过,因为它找不到任何fieldinfos。
我检查了所有绑定标志的所有成员(实例,静态,公共,非公开),但它没有找到任何东西。
问题是为什么?我如何初始化动态创建的类的字段?
public class DynamicObject
{
public Type GeneratedType;
public object Instance;
public DynamicObject(Type BaseType)
{
//create object with Name: BaseType.Name + "_dynamic", in module "dynamic in assembly "dynamic"
System.Reflection.Emit.TypeBuilder tb = AppDomain.CurrentDomain.DefineDynamicAssembly(new System.Reflection.AssemblyName("dynamic"), System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave).DefineDynamicModule("dynamic").DefineType(BaseType.Name + "_" + "dynamic", System.Reflection.TypeAttributes.Public);
foreach (System.Reflection.FieldInfo fi in BaseType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
//create public field-definitions with identical Name
tb.DefineField(fi.Name, fi.FieldType, System.Reflection.FieldAttributes.Public);
}
//save type
this.GeneratedType = tb.CreateType();
//create Instance with standard constructor: public <Type>_dynamic()
this.Instance = tb.GetConstructor(Type.EmptyTypes).Invoke(new object[] { });
//initialize fields through BaseType fields
foreach (System.Reflection.FieldInfo fi in this.Instance.GetType().GetFields(System.Reflection.BindingFlags.Public))
{
//load value from static variables
fi.SetValue(this.Instance, BaseType.GetField(fi.Name).GetValue(null));
}
}
}