【问题标题】:How to reference a static field declared in generic base class when creating subclass using emit?使用emit创建子类时如何引用泛型基类中声明的静态字段?
【发布时间】:2011-10-28 17:06:11
【问题描述】:

这是(非常简化的)示例:

public abstract class BaseClass<T> where T : BaseClass<T>
{
    public static SomeOtherClass MyStaticField = new SomeOtherClass(typeof(BaseClass<T>));
}

public sealed class FinalClass : BaseClass<FinalClass>
{
    static FinalClass()
    {
        MyStaticField.SomeProperty = 123;
    }
}

BaseClass 是用代码编写并编译的。我需要使用 Emit 在运行时创建 FinalClass。我设法发布了Is it possible to emit a type deriving from a generic type while specifying itself as the generic type parameter?中讨论的课程。

问题是我在发射时无法引用字段 MyStaticField。我尝试使用 TypeBuilder.GetField 但它不起作用,因为我的类型仍在“建设中”并且尚未最终确定。我尝试使用 typeof(BaseClass).MakeGenericType(typeBuildOfFinalClass) 但出于同样的原因它不起作用。

当我手动编写代码并反编译时,我看到了对 BaseClass.MyStaticField 的引用,但我找不到发出它的方法。我不知道如何获取发出操作码函数参数所需的 FieldInfo。

有谁知道我该如何解决这个问题?

谢谢。

附:对于使用 emit... 的任何人,您可能会发现这非常有用 (http://www.codeproject.com/KB/msil/emithelper.aspx)。这是一个非常古老的消息,但如果你不知道......试试吧:)

【问题讨论】:

  • 在某些时候你必须指定基类......所以你应该仍然有那个类型吗?

标签: .net generics static-members reflection.emit


【解决方案1】:

你需要使用静态TypeBuilder.GetField方法:

var fieldInfo = TypeBuilder.GetField(typeof(BaseType<>).MakeGenericType(typeBuilderOfFinalClass), typeof(BaseType<>).GetField(...))

【讨论】:

  • 我没有注意到 TypeBuilder 也有静态 GetField 方法。它工作得很好。谢谢。
猜你喜欢
  • 2011-09-28
  • 1970-01-01
  • 2023-01-09
  • 2020-02-15
  • 2012-06-14
  • 2019-05-01
  • 1970-01-01
  • 2015-09-30
  • 2011-05-04
相关资源
最近更新 更多