用"this"链接的构造函数

4 c# c#-3.0

为什么ClassA中的第一个构造函数会导致编译器错误"无法使用"这个"在成员初始化程序中"?

......或者我怎样才能让它发挥作用?

谢谢

public sealed class ClassA : IMethodA
{
    private readonly IMethodA _methodA;

    public ClassA():this(this)
    {}

    public ClassA(IMethodA methodA)
    {
        _methodA = methodA;
    }

    public void Run(int i)
    {
        _methodA.MethodA(i);
    }

    public void MethodA(int i)
    {
        Console.WriteLine(i.ToString());
    }
}

public interface IMethodA
{
    void MethodA(int i);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 9

您可以使用该this(...)语法在同一级别调用另一个构造函数 - 但是,您不能this在此上下文中使用(当前实例).

这里最简单的选择是复制赋值代码(_methodA = methodA).

另一个选项可能是null-coalescing:

public ClassA():this(null)
{}

public ClassA(IMethodA methodA) 
{ // defaults to "this" if null
    _methodA = methodA ?? this;
}
Run Code Online (Sandbox Code Playgroud)