2013-05-03 21 views
-1

我需要將日期參數傳遞給可能具有不同日期的方法 例如日期可能是expirydate或createddate?爲同一方法傳遞不同的日期值

我如何傳遞給方法

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

我僅限於.NET 4.0框架。

+0

非常不清楚你是什麼尋找 - 你已經可以傳遞任何你想要的日期到一個方法,需要'DateTime'作爲參數... – 2013-05-03 18:14:08

回答

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()擁有一個虛擬方法,任何事物都可以調用而不必打開type/enum。

它也保持不同的邏輯不同種類的日期完全獨立:

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
void dosomething(DateTime? dateVal, int datetype ) 
    { 
//datetype could be 1= expire , 2 = create , etc 
    // doawesomehere 
    } 
+4

不要使用這個魔術整數。至少使用Enum,雖然我不確定這種方法在這裏是否合適。 – Servy 2013-05-03 18:16:01

+0

這似乎應該重新考慮這個功能,並希望推廣。 – will 2013-05-03 18:18:04

0

這很不清楚你想要什麼。

如果你想有一個功能,將做一些事情來一個DateTime,那麼你會做這樣的:

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

和你使用它像:

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

如果您想要一個可以對不同的DateTime做不同的事情,這取決於它們代表什麼,你應該把它分成不同的功能。

相關問題