简体   繁体   中英

Can I use OpCodes.Ldsfld without using FieldInfo?

I want to avoid using GetType and GetField. Can I just use a string with Ldsfld? I have included a mock-up of what I'm trying to accomplish below. As you can see I'm new to IL Generation - I'm trying to remove some of the cost the cost of reflection in my application.

using System;
using System.Reflection.Emit;

namespace ConsoleApplication10
{
    static class Program
    {
        public static string TextBox1 = "Hello World!";

        static void Main(string[] args)
        {
            var dm = new DynamicMethod("My_method",
                typeof(string), null, true);

            var il = dm.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, "string ConsoleApplication10.Program::TextBox1");
            il.Emit(OpCodes.Ret);
            var func = (Func<string>)dm.CreateDelegate(typeof(Func<string>));
            var s = func();

            Console.WriteLine(s);
        }
    }
}

No, you can't, the documentation for OpCodes.Ldsfld says:

The following Emit method overload can use the ldsfld opcode:

  • ILGenerator.Emit(OpCode, FieldInfo)

And to get FieldInfo if you know the name of the field, you need to use reflection.

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