我正在尝试访问正在定义Methodbuilder方法的类的属性。这是我目前的代码:
Type[] types = { typeof(HttpListenerContext) };
TypeBuilder tb = GetTypeBuilder(type.Name);
ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
MethodBuilder mB = tb.DefineMethod("Init", MethodAttributes.Public | MethodAttributes.Virtual, null, types);
ILGenerator il = mB.GetILGenerator();
il.Emit(OpCodes.Ldstr, typeof(Page).GetProperty("_POST").GetValue(??));
il.Emit(OpCodes.Call, typeof(DataSet).GetMethod("SetData"));
il.Emit(OpCodes.Ret);
tb.DefineMethodOverride(mB, typeof(Page).GetMethod("Init"));
try
{
Type tc = tb.CreateType();
Page test = (Page)Activator.CreateInstance(tc);
test.Init();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}这是我想要从以下方面获得的类:
public class Page
{
public Dictionary<string, string> _POST { get; set; }
public Dictionary<string, string> _GET { get; set; }
public Head Headers { get; set; }
public string ContentType { get; set; }
public int StatusCode = 200;
public virtual void Init(HttpListenerContext ctx = null) { }
public virtual void Load() { }
public virtual string Send() { return ""; }
public virtual string Send(string response) { return ""; }
}当前的类型生成器以Page作为父类,如何在我的类型生成器类中获得一个非静态值?就像我怎样才能让我的方法Console.WriteLine _POST的值?
private TypeBuilder GetTypeBuilder(string name)
{
string typeSignature = name;
AssemblyName aN = new AssemblyName(typeSignature);
AssemblyBuilder aB = AppDomain.CurrentDomain.DefineDynamicAssembly(aN, AssemblyBuilderAccess.Run);
ModuleBuilder mB = aB.DefineDynamicModule("MainModule");
TypeBuilder tB = mB.DefineType(typeSignature + "h",
TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout,
typeof(Page));
return tB;
}
ILGenerator il = mB.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, typeof(Page).GetProperty("ContentType").GetGetMethod());
il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
il.Emit(OpCodes.Ret);
tb.DefineMethodOverride(mB, typeof(Page).GetMethod("Init"));在用函数获取ContentType之前,我正在设置它的值。
发布于 2015-11-30 09:59:42
您似乎在从Page继承的类型上创建实例方法。如果是这样的话,这就是您想要的代码:
il.Emit(OpCodes.Ldarg_0); // Load the this reference
il.Emit(OpCodes.Call, typeof(Page).GetProperty("_POST").GetGetMethod());另外,请注意,DataSet没有SetData方法--如果这是一个扩展方法,则需要使用定义它的真实类型,而不是DataSet。
https://stackoverflow.com/questions/33995670
复制相似问题