I need help with .Net Reflection.Emit
.
Need create simple Assembly
with public struct
and string
field in it. Field must be constant and I also need define it. In all I need get Assembly
that hold inside something like this:
namespace n {
struct Alpha {
public const string DATA = "Alpha";
}
}
I don't understand how create string
field and how define it.
At this moment i am write this code:
private static void Generate()
{
var an = new AssemblyName("Beta") { Version = new Version("1.0.0.0") };
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Save);
var mb = ab.DefineDynamicModule("BetaModule", "Beta.dll");
var tb = mb.DefineType("n.Beta", TypeAttributes.Public, typeof(System.ValueType));
// What I need do after it? How I understand from MSDN I need call DefineInitializedData method but i am not shure how do it.
tb.CreateType();
ab.Save("Beta.dll");
}
Solution:
private static void Generate() {
var an = new AssemblyName("Beta") { Version = new Version("1.0.0.0") };
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Save);
var mb = ab.DefineDynamicModule("BetaModule", "Beta.dll");
var tb = mb.DefineType("n.Beta", TypeAttributes.Public, typeof(System.ValueType));
var fb = tb.DefineField("DATA", typeof(string), FieldAttributes.Public | FieldAttributes.Literal);
fb.SetConstant("Beta");
tb.CreateType();
ab开发者_如何学编程.Save("Beta.dll");
}
I am not sure that it is 100% correct, but it works. BTW, it would be great if some one will check it. Maybe I made some mistakes...
Constants have no meaning in IL. They are compiled by the compiler, it emits their literal value into the IL. You are playing the role of the compiler when you use Reflect.Emit, you have emit the value yourself.
Which isn't a real problem, you can just declare the const in your own code. And emit the ldc or ldstr opcode whenever the const needs to be used.
精彩评论