为什么我的成员变量在构造后为null?

huangapple go评论80阅读模式
英文:

Why are my member variables null after construction?

问题

我有一个简单的C#类构造函数,我正在通过单元测试运行它。有两个成员:

public class AnObject
{
    private Func<List<string>> function;
    private SHA256 sha256;

和一对嵌套的构造函数:

    public AnObject()
    {
        new AnObject(InternalFunction);
    }
    
    public AnObject(Func<List<string>> function)
    {
        this.function = function;
        this.sha256 = SHA256.Create();
    }

其中第一个构造函数将函数传递给第二个:

    private List<string> InternalFunction()
    {
        return ...
    }
}

在第二个构造函数中,被第一个构造函数调用时,类成员被正确设置。但当焦点回到第一个构造函数时,两个成员变量都恢复为 'null'。为什么?

在Visual Studio Community 2022中调试单元测试。

英文:

I have a simple C# class constructor I'm running through a unit test. There are two members:

public class AnObject
{
    private Func&lt;List&lt;string&gt;&gt; function;
    private SHA256 sha256;

and a pair of nested constructors:

    public AnObject()
    {
        new AnObject(InternalFunction);
    }
    
    public AnObject(Func&lt;List&lt;string&gt;&gt; function)
    {
        this.function = function;
        this.sha256 = SHA256.Create();
    }

the first of which passes the function

    private List&lt;string&gt; InternalFunction()
    {
        return ...
    }
}

to the second.

While within the second constructor having been called from the first, the class members are being set correctly. When focus breaks back to the first constructor, both member variables revert to 'null'. Why?

Debugging unit test in Visual Studio Community 2022.

答案1

得分: 3

因为这不是构造函数链的工作方式。而是在第一个构造函数中创建了一个与另一个实例无关的全新实例。

请改用以下方式:

public AnObject() : this(InternalFunction) { }    
public AnObject(Func<List<string>> function)
{
    this.function = function;
    this.sha256 = SHA256.Create();
}
英文:

because that's not how constructor-chaining works. Instead of chaining them together, you're effectivly creating a completely new instance of your type within your first constructor, that has nothing to do with the other instance.

Use this instead:

public AnObject() : this(InternalFunction) { }    
public AnObject(Func&lt;List&lt;string&gt;&gt; function)
{
    this.function = function;
    this.sha256 = SHA256.Create();
}

答案2

得分: 3

你在无参数构造函数中创建了一个新对象,而没有调用其他构造函数。尝试改成这样:

public AnObject() : this(InternalFunction)
{

}
英文:

You are creating a new object in your parameterless constructor, not calling the other. Try this instead

public AnObject() : this(InternalFunction)
{

}

huangapple
  • 本文由 发表于 2023年7月31日 22:34:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定