MyFunctions MyFormulas = new MyFunctions();
类MyFunctions
{
public double Rectangle[](double Length, double Width)
{
double[] Rectangle=new double[1];
double AreaOfRectangle = Length * Width;
double PerimeterOfRectangle = 2 * (Length + Width);
Rectangle[0]=AreaOfRectangle;
Rectangle[1]=PerimeterOfRectangle;
return Rectangle;
}
}
我需要这样的东西。在1类下返回2个值。这有可能吗?
答案 0 :(得分:2)
你有一些问题:
[]
)附加到类型(double
),而不是方法; 现在是工作代码:
public double[] Rectangle(int Length, int Width)
{
double[] rect = new double[2];
double areaOfRectangle = Length * Width;
double perimeterOfRectangle = 2 * (Length + Width);
rect[0] = areaOfRectangle;
rect[1] = perimeterOfRectangle;
return rect;
}
这样称呼:
MyFunctions mf = new MyFunctions();
double[] d = mf.Rectangle();
double areaOfRectangle = d[0];
double perimeterOfRectangle = d[1];
在其他情况下,您可能需要Tuple
实例,自定义类或结构实例作为返回类型或out
参数。
这样的东西也是一个选项(使用自定义类SpecialRectangle
):
public class SpecialRectangle
{
double AreaOfRectangle { get; set; }
double PerimeterOfRectangle { get; set; }
}
public SpecialRectangle Rectangle(double Length, double Width)
{
return new SpecialRectangle() { AreaOfRectangle = Length * Width, PerimeterOfRectangle = 2 * (Length + Width) };
}
这样称呼:
MyFunctions mf = new MyFunctions();
SpecialRectangle s = mf.Rectangle();
double areaOfRectangle = s.AreaOfRectangle;
double perimeterOfRectangle = s.PerimeterOfRectangle;