我正在阅读 Data Structures and Algorithms Using C# (Michael McMillan)。
在第 3 章第 43 页中,我发现代码片段在构造函数中接受参数但创建对象时不传递任何内容。
这可能吗?
最佳答案
可能有几种可能性:
- 打字错误
还有一个过载
public CArray(int size) { // Implementation. } public CArray() { // Other implementation. }
可以有默认值
public CArray(int size = 8) { // Implementation. }
即使问题中提供的代码不会“按原样”编译(没有 3 种解释之一 - 有一种方法可以创建未初始化的实例使用 System.Runtime.Serialization.FormatterServices
根本没有构造函数调用:
class SomeType
{
int mVariable;
public SomeType(int size)
{
mVariable = size;
}
}
static void Main(string[] args)
{
Type someType = typeof(SomeType);
SomeType instance = (SomeType)FormatterServices.GetUninitializedObject(someType);
// instance.mVariable = 0;
}
请记住,此方法速度慢且不安全,因为您可能会以其开发人员不希望您手动覆盖构造函数的方式使用 class
,因此 它应该仅用于序列化目的,而不是用于一般初始化。
关于c# - 在不传递参数的情况下创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39384355/