假设我有这样一个类:
public class Fraction
{
int numerator;
int denominator;
public Fraction(int n, int d)
{
// set the member variables
}
// And then a bunch of other methods
}
Run Code Online (Sandbox Code Playgroud)
我想以一种很好的方式初始化它们的数组,这篇文章是一个很容易出错或语法上很麻烦的方法列表.
当然数组构造函数会很好,但是没有这样的东西:
public Fraction[](params int[] numbers)
Run Code Online (Sandbox Code Playgroud)
所以我被迫使用像这样的方法
public static Fraction[] CreateArray(params int[] numbers)
{
// Make an array and pull pairs of numbers for constructor calls
}
Run Code Online (Sandbox Code Playgroud)
这是相对笨重的,但我没有看到解决方法.
这两种形式都容易出错,因为用户可能错误地传递了奇数个参数,可能是因为他/她跳过了一个值,这会让这个函数不知所措地想知道用户究竟想要什么.它可能会抛出异常,但用户需要尝试/ catch.如果可能的话,我宁愿不对用户施加压力.所以让我们强制执行配对.
public static Fraction[] CreateArray(params int[2][] pairs)
Run Code Online (Sandbox Code Playgroud)
但你不能以一种很好的方式调用这个CreateArray,比如
Fraction.CreateArray({0,1}, {1,2}, {1,3}, {1,7}, {1,42});
Run Code Online (Sandbox Code Playgroud)
你甚至做不到
public static Fraction[] CreateArray(int[2][] pairs)
// Then …Run Code Online (Sandbox Code Playgroud)