gpt4 book ai didi

C#构造函数问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:06 26 4
gpt4 key购买 nike

我有一个关于 C# 的构造函数问题。

我有这门课:

public partial class Signature : Form, ISignature
{
private readonly SignatureMediator mediator;

public Signature(SignatureMediator mediator)
{
this.mediator = mediator;
InitializeComponent();
}

.... more stuff
}

我想像这样构造这个类:

    public SignatureMediator(int someValue, int otherValue, int thirdValue)  
: this(new Signature(this), someValue, otherValue, thirdValue)
// This is not allowed --^
{
// I don't see anyway to get this in to the ":this" part.
//Signature signature = new Signature(this);

}


public SignatureMediator(ISignature form, int someValue, int otherValue, int thirdValue)
{
SigForm = form;
SomeValue= someValue;
OtherValue= otherValue;
ThirdValue= thirdValue;
}

The : this( new SignatureThis(this) is not allowed (the this used in the constructor is not allowed).

有没有办法在不重复分配 int 值的情况下进行设置?

最佳答案

如果 ISignature 参数为 null,如何让第二个构造函数从 this 构造一个 Signature,否则使用提供的 ISignature?然后您可以从第一个构造函数传递 null 以获得您想要的行为。

public SignatureMediator(int someValue, int otherValue, int thirdValue)  
: this(null, someValue, otherValue, thirdValue)
{
}

public SignatureMediator(ISignature form, int someValue, int otherValue, int thirdValue)
{
if (form == null)
{
SigForm = new Signature(this);
}
else
{
SigForm = form;
}

SomeValue = someValue;
OtherValue = otherValue;
ThirdValue = thirdValue;
}

关于C#构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2633853/

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