英文:
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<List<string>> function;
private SHA256 sha256;
and a pair of nested constructors:
public AnObject()
{
new AnObject(InternalFunction);
}
public AnObject(Func<List<string>> function)
{
this.function = function;
this.sha256 = SHA256.Create();
}
the first of which passes the function
private List<string> 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<List<string>> 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)
{
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论