我想避免使用 GetType 和 GetField。我可以只在 Ldsfld 中使用字符串吗?我在下面提供了我想要完成的任务的模型。正如您所看到的,我是 IL Generation 的新手 - 我正在尝试消除应用程序中反射成本的一些成本。
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);
}
}
}
最佳答案
不,你不能,the documentation for OpCodes.Ldsfld
说:
The following
Emit
method overload can use theldsfld
opcode:
ILGenerator.Emit(OpCode, FieldInfo)
如果您知道字段名称,则要获取 FieldInfo
,则需要使用反射。
关于c# - 我可以在不使用 FieldInfo 的情况下使用 OpCodes.Ldsfld 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36142513/