Reputation: 31
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);
}
}
}
Upvotes: 2
Views: 473
Reputation: 245028
No, you can't, the documentation for OpCodes.Ldsfld
says:
The following
Emit
method overload can use theldsfld
opcode:
ILGenerator.Emit(OpCode, FieldInfo)
And to get FieldInfo
if you know the name of the field, you need to use reflection.
Upvotes: 2