简体   繁体   中英

Convert C# code

I need to simulate in C# code (with ilGenerator.Emit) the following function

public void AssignAttribute(ref ValueHolder output, Assignment assignment) {
    ResultAttribute attribute = null;

    if ( (attribute = output.MultipleResults.Find(delegate(ResultAttribute o) {
        return o.Name == assignment.Name;
    })) != null)
        attribute.Value = assignment.Value;
    }

Can anybody help me?

The thing to do is to compile the method in a project C#, then have a look at the IL in the assembly it generates using Reflector . You can easily replicate that IL using Emit and make whatever dynamic changes you need.

c# create a closure (see wikipedia if you not familiar with) for you since in the anonymous method body you reference to the assignment variable (which is parameter in your case but this doesn't matter).

You need to create class holder for anonymous delegate (at least c# compiler does this)

then you need to create field in this class since your delegate closeover (i'm not native english so here maybe misspelling ) Assignment assignment parameter

Then in the body of AssignAttribute you should emit class instaniation IL_0000: newobj instance void V24.Generated.Worker/'<>c__DisplayClass1'::.ctor()

as well as feild assignment IL_0008: stfld class [nviss]NViss.Assignment V24.Generated.Worker/'<>c__DisplayClass1'::assignment

note that since filed initialization finished anywhere access to local variable was replaced with access to field

once again sorry for my English

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM