Cannot use 'this' in member initializer?

后端 未结 3 944
一整个雨季
一整个雨季 2020-12-11 17:12

Is this legal? Does it contain a hidden bug or flaw? Visual studio does not give any errors or warnings but ReSharper does:

/// 
/// immutable         


        
相关标签:
3条回答
  • 2020-12-11 17:54

    This is a bug in the C# 3 compiler that is fixed in C# 4.

    Edit:
    Corner case in using lambdas expression in base constructor

    0 讨论(0)
  • 2020-12-11 18:12

    I'm pretty sure I've heard that this is a compiler bug, fixed in the next release. I'm just firing up my 4.0 VM, with a simpler test-case:

    class Foo {
        public Foo() : this(delegate { this.Bar(); }) { }
        public Foo(Action foo) {}
        public void Bar() {}
    }
    

    works in VS2008, but in VS2010:

    Error 1 Keyword 'this' is not available in the current context

    0 讨论(0)
  • 2020-12-11 18:13

    Your constructor will loop forever, until it pops the stack. This is because it keeps calling itself recursively. Try splitting it up:

    public Pair(TValue1 value1, TValue2 value2)
        : this(value1, value2, () => toStringFunc(this)) { }
    
    public Pair(TValue1 value1, TValue2 value2, Func<Pair<TValue1, TValue2>, String> toStringFunc)
        { /* some actual logic */ }
    
    0 讨论(0)
提交回复
热议问题