views:

30

answers:

1

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); // ToDo добавить путь к дирректории bin/debug проекта etalon

        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 its work. BTW, it will be great if some one would check it. Maybe i am make some mistakes?

+1  A: 

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.

Hans Passant
If i am understand you right i cant make const by emit but i can make readonly field and declare it in constructor. Right?
t.zamaleev
Think this through a bit: why not declare the const in your own code?
Hans Passant
Ok, readonly field will also good. But what i need do to make it?1. Create field by DefineField method or by DefineInitializedData?2. Create default constructor for struct3. In constructor define fieldAll right?What flag i need use to create readonly field? FieldAttributes.Literal?
t.zamaleev
I get how to do this, thank you very much!
t.zamaleev