Cannot use 'this' in member initializer?

戏子无情 提交于 2019-11-27 07:44:07

问题


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

/// <summary>
/// immutable tuple for two
/// </summary>
public class Pair<TValue1, TValue2> : Singleton<TValue1>
{
    public TValue2 Value2 { get; private set; }
    public Pair(TValue1 value1, TValue2 value2, Func<Pair<TValue1, TValue2>, String> toStringFunc)
        : this(value1, value2, () => toStringFunc(this)) { } //Red light

}2> : Singleton<TValue1>

回答1:


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




回答2:


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




回答3:


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 */ }


来源:https://stackoverflow.com/questions/2023640/cannot-use-this-in-member-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!