gpt4 book ai didi

c# - 构造函数链接 "this"

转载 作者:行者123 更新时间:2023-12-04 21:55:20 25 4
gpt4 key购买 nike

为什么 ClassA 中的第一个构造函数会导致编译器错误“不能在成员初始化器中使用“this”?

...或者我怎样才能让它工作?

谢谢

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);
}

最佳答案

您可以使用 this(...)在同一级别调用另一个构造函数的语法 - 但是,您不能使用 this (当前实例)在这种情况下。

这里最简单的选择是复制分配代码( _methodA = methodA )。

另一种选择可能是空合并:

public ClassA():this(null)
{}

public ClassA(IMethodA methodA)
{ // defaults to "this" if null
_methodA = methodA ?? this;
}

关于c# - 构造函数链接 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/681410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com