我正在使用 Reflection.Emit 来定义动态类型。该类继承自通用基类。在 C# 中,这一切看起来像这样:
public abstract class DataReaderMapper<T>
{
protected readonly IDataReader reader_;
protected DataReaderMapper(IDataReader reader) {
reader_ = reader;
}
}
public class SomeDataReaderMapper: DataReaderMapper<ISomeInterface> {
public string SomeProperty {
get { return reader_.GetString(0); }
}
}
Reflection.Emit 部分:
Type MakeDynamicType() {
TypeBuilder builder = module_.DefineType(
GetDynamicTypeName(),
TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AutoLayout,
typeof (DataReaderMapper<T>),
new Type[] {type_t_});
ConstructorBuilder constructor =
type.DefineConstructor(MethodAttributes.Public |
MethodAttributes.HideBySig |
MethodAttributes.SpecialName |
MethodAttributes.RTSpecialName,
CallingConventions.Standard, new Type[] {typeof (IDataReader)});
ConstructorInfo data_reader_mapper_ctor = typeof (DataReaderMapper<T>)
.GetConstructor(new Type[] {typeof (IDataReader)});
ILGenerator il = constructor.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Call, data_reader_mapper_ctor);
il.Emit(OpCodes.Ret);
PropertyBuilder property_builder = builder
.DefineProperty(property.Name, PropertyAttributes.HasDefault,
property.PropertyType, null);
MethodBuilder get_method = builder.DefineMethod("get_" + property.Name,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig);
ILGenerator il = get_method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
// *********************
// How can I access the reader_ field of the base class.
// *********************
property_builder.SetGetMethod(get_method);
}
问题是我正在尝试使用 Reflection.Emit 动态生成 SomeDerivedDataMapper,但我不知道如何访问基类的受保护字段。显然可以生成代码来执行此操作,因为 C# 代码工作得很好。我想编译器可能会做一些实际上不受 Reflection.Emit 支持的事情,但我希望这不是其中一种情况。
在这种情况下,有人知道如何访问基类中的字段吗?
谢谢你的帮助