Hi Zoury,
Based on my understanding, you want to dynamically create a Enum and set
its value correctly.
Yes, the article way of using Reflection.Emit is correct, but when setting
its value, I think we should not use Type.GetNestedType method.
Type.GetNestedType method searches for the nested type with the specified
name. But for the Enum, the "pawn" is not a nested type, it is just a
nested field. So Type.GetNestedType method will always return null.
FieldInfo.SetValue method's second parameter is "The value to assign to the
field". Because it is a Enum type, you should specify Enum object for it,
you should not specify a type object for it.
So, you should do like this:
AppDomain ad = AppDomain.CurrentDomain;
AssemblyName an = new AssemblyName();
an.Name = "MyDynamicAssembly";
AssemblyBuilder ab = ad.DefineDynamicAssembly(an,
AssemblyBuilderAccess.Run);
ModuleBuilder mb = ab.DefineDynamicModule("MyDynamicModule");
TypeBuilder tb = mb.DefineType("MyDynamicClass");
EnumBuilder eb = mb.DefineEnum("enumChess",
TypeAttributes.Public,typeof(int));
eb.DefineLiteral("pawn", 0);
eb.DefineLiteral("castle", 1);
eb.DefineLiteral("king", 2);
Type tEnum = eb.CreateType();
if (tEnum != null)
{
FieldBuilder fb = tb.DefineField("theChess", tEnum,
FieldAttributes.Public);
Type tClass = tb.CreateType();
if (tClass != null)
{
object o = Activator.CreateInstance(tClass);
FieldInfo fi = tClass.GetField("theChess");
object enumvalue=Enum.Parse(tEnum, "king");
fi.SetValue(o, enumvalue);
string s = fi.GetValue(o).ToString();
MessageBox.Show(s);
}
}
It works well on my machine.
========================================
Please apply my suggestion above and let me know if it helps resolve your
problem.
Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.
Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! -
www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.