我想调用一个结构体的构造函数,该构造函数对所有参数都有默认值。但当我调用MyRectangle的无参构造函数时,会调用一个未定义的构造函数。为什么会这样?有没有不调用由我创建的构造函数的方法?
using System;
namespace UebungClasses
{
class Program
{
static void Main(string[] args)
{
MyRectangle sixRec = new MyRectangle(3, 2);
MyRectangle oneRec = new MyRectangle();
Console.WriteLine("area of six: " + sixRec.Area() + " area of one: " + oneRec.Area());
}
}
public struct MyRectangle
{
public MyRectangle(double w = 1, double l = 1)
{
width = w;
length = l;
Console.WriteLine("Width: " + width + " Lenght: " + length);
}
public double Area()
{
return width * length;
}
private double width;
private double length;
}
}
MyRectangle
是一个class
而不是struct
,它将按照您的意图工作。但由于历史原因,任何使用new T()
其中T
是值类型,都与default(T)
相同。 - Jeppe Stig Nielsen