【问题标题】:Passing different date values for the same method为同一方法传递不同的日期值
【发布时间】:2013-05-03 18:10:43
【问题描述】:

我需要将日期参数传递给可能具有不同日期的方法 例如日期可能是过期日期或创建日期?

我如何传递给一个方法

void dosomething(?datetime whateverthedate)
{
// doawesomehere
}

我仅限于 .net 4.0 框架。

【问题讨论】:

  • 非常不清楚您在寻找什么 - 您已经可以将任何日期传递给以 DateTime 作为参数的方法...

标签: c# oop function parameter-passing


【解决方案1】:

这就是你的做法:

void DoSomethingWithExpiryDate(DateTime expiryDate)
{
    ...
}

void DoSomethingWithCreatedDate(DateTime createdDate)
{
    ...
}

我知道这似乎有点滑稽,但你明白了。

但除此之外,请考虑将两条数据(日期和种类)包装到一个类中,然后传递该类的一个实例:

enum DateItemKind
{
    ExpiryDate,
    CreatedDate
}

class DateItem
{
    public DateTime DateTime { get; set; }
    public DateItemKind Kind { get; set; }
}

void DoSomething(DateItem dateItem)
{
    switch (dateItem.Kind)
    ...

等等,还有更多!

每当我看到这样的类型/枚举切换时,我都会想到“虚拟方法”。

因此,也许最好的方法是使用抽象基类来捕获共性,并为 DoSomething() 提供一个虚拟方法,任何东西都可以调用,而无需打开类型/枚举。

它还使不同类型日期的不同逻辑完全分开:

abstract class DateItem
{
    public DateTime DateTime { get; set; }

    public abstract virtual void DoSomething();
}

sealed class CreatedDate: DateItem
{
    public override void DoSomething()
    {
        Console.WriteLine("Do something with CreatedDate");
    }
}

sealed class ExpiryDate: DateItem
{
    public override void DoSomething()
    {
        Console.WriteLine("Do something with ExpiryDate");
    }
}

那么你可以直接使用DoSomething(),不用担心类型:

void DoStuff(DateItem dateItem)
{
    Console.WriteLine("Date = " + dateItem.DateTime);
    dateItem.DoSomething();
}

【讨论】:

    【解决方案2】:

    不清楚你想要什么。

    如果您想要一个对DateTime 执行某些操作的函数,那么您可以这样做:

     public DateTime AddThreeDays(DateTime date)
     {
         return DateTime.AddDays(3);
     }
    

    你会像这样使用它:

     DateTime oldDate = DateTime.Today;
     DateTime newDate = AddThreeDays(oldDate);
    

    如果你想要一个对不同的DateTimes 做不同的事情,取决于它们代表什么,你应该把它分成不同的功能。

    【讨论】:

      【解决方案3】:
          void dosomething(DateTime? dateVal, int datetype  )
          {
      //datetype could be 1= expire , 2 = create  , etc 
          // doawesomehere
          }
      

      【讨论】:

      • 不要为此使用魔法整数。至少使用枚举,尽管我不确定这种方法是否适合这里。
      • 似乎应该重新考虑这个功能,并希望能够推广。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      相关资源
      最近更新 更多