从函数返回2个值?

时间:2014-11-02 04:56:08

标签: c#

我有一个代表预定付款的对象。我的数据库有这些付款的清单,但我有一个付款实例。

我需要编写一种方法,在我拥有的方式之后获得下一笔付款,以及之前付款的上一个日期。

我想编写一个返回两个日期的方法。但是返回类型为&#39; DateTime&#39;只允许一个。我可以返回一个List<DateTime>,但这看起来很奇怪而且可能含糊不清。哪个是前一个,哪个是下一个?

我还可以创建一个DTO对象:

DateTime previousPayment {get; set;}
DateTime nextPayment {get; set;}

Tuple<DateTime, DateTime>可能是另一种选择,但它也是含糊不清的。除非我可以命名它的属性?

但是 - 是否有更好的方法允许方法返回两个日期?匿名类型还是什么?

4 个答案:

答案 0 :(得分:3)

使用&#34; ref&#34;修改。 (您可以使用&#34; out&#34;相反,如果您在分配变量之前不需要读取变量)

public void GetNextPayment(ref DateTime previousPayment, ref DateTime nextPayment){
    // do stuff here
}

用法:

DateTime previousPayment = DateTime.Now(); //Example
DateTime nextPayment = DateTime.Now(); // example
GetNextPayment(ref previousPayment, ref nextPayment); // Forgot to add "ref" when calling it

previousPayment和nextPayment将在函数中修改并保持该值。

使用词典更新

正如Anik所说,使用词典可能更好;

public Dictionary<string,DateTime> GetNextPayment(DateTime previousPayment, DateTime nextPayment){
    // modify payments
    Dictionary<string,DateTime> myDict = new Dictionary(string, DateTime);
    myDict.Add("PreviousPayment", [date]);
    myDict.Add("NextPayment", [date]);
    return myDict;
}

使用课程

伊利亚安德。 N.提到要使用一个类。如果您要使用多个付款对象不止一次,我将不得不同意这一点。但我坚信最好能为您提供所有可用的工具,因为您永远不知道何时可能需要使用参数或词典。

public class Payment {
    public string Name {get;set;}
    public DateTime previousPayment {get;set;}
    public DateTime nextPayment {get;set;}

    public GetNextPayment(){
        // code to get the next payment
        this.previousPayment = //whatever
        this.nextPayment = //whatever
    }
}

如果您只有一次付款,您将会像往常一样使用。 (对于未来的课程证明是好的),那么你可以使用方法或字典。

答案 1 :(得分:1)

为什么不简单地返回课程?

public class DateCombo {
DateTime PreviousPayment {get; set;}
DateTime NextPayment {get; set;}

}

答案 2 :(得分:1)

除了您列出的两个选项外,还有两个选项:

  1. 返回Tuple<DateTime, DateTime>
  2. 使用out参数

答案 3 :(得分:0)

试试这个......

private void Form1_Load(object sender, EventArgs e)
    {
        DateTime previousPayment =new DateTime();
        DateTime nextPayment=new DateTime();
        getdate(ref previousPayment, ref nextPayment);
    }
    public void getdate(ref  DateTime previousPayment, ref DateTime nextPayment)
    {
        previousPayment = System.DateTime.Now;
        nextPayment = System.DateTime.Now.AddDays(1);

    }