直接初始化class成员变量时"this"不可用

"this" is unavailable when directly initializing class member variable

为什么编译器在定义实例变量时初始化时报this being unavailable?

Keyword 'this' is not available in the current context

构造函数初始化没问题。我了解这里的情况 - 我只是想找到原因(通过 MSDN 或其他方式)为什么 "this" 可用于构造函数但如果初始化成员变量则不能直接使用。

这是我看到的错误的简单抽象。

public class ClassA
{
    // Gets compiler error that "this" unavailable
    protected ClassB _a1 = new ClassB(this);

    // Works fine
    protected ClassB _a2;
    public ClassA() { _a2 = new ClassB(this); }
}

public class ClassB
{
    public ClassA A { get; private set; }
    public ClassB(ClassA a) { this.A = a; } 
}

我希望将初始化放在赋值旁边,因为上面的示例是我的代码的抽象,我在其中为 10-15 个成员变量定义 Lazy valueFactory 委托,其中委托需要将数据上下文作为构造函数的参数。对于 15 个成员变量,我更愿意将赋值保留在定义旁边的一行中,而不是有 15 行定义,然后在构造函数中另外 15 行初始化每个。

这基本上是我在实际代码中必须做的:

public class MyContext
{
    public ProgramService Programs { get { return _programs.Value; } }
    protected Lazy<ProgramService> _programs;

    public MyContext()
    {
        _programs = new Lazy<ProgramService>(() => new ProgramService(this));
    }
}

基本上是为了防止您依赖订单 (textual) 和可能无法使用的正在建设中的 class 状态。我认为最重要的原则是,如果它是 "complicated" 逻辑,那么您应该使用构造函数。

例如,这样做:

class A {
   private int x = 1;
   private int y = this.x + 1;
}

会导致与以下不同的结果:

class A {
   private int y = this.x + 1;
   private int x = 1;
}

有点出乎意料。为了回避这个问题,但仍然允许内联初始化的便利——不允许 this 使得顺序无关紧要。

在您的实际代码中,您可能会进行惰性检查以将所有内容放在一起:

public ProgramService Programs { 
   get { 
      if (_programs == null) _programs = new ProgramService(this);
      return _programs.Value; 
   } 
}
// change this to private to keep subclasses from accessing a possibly null reference
private Lazy<ProgramService> _programs;