簡體   English   中英

方法重載-區分Nullable DateTime和String參數

[英]Method overloading -Distinguish between Nullable DateTime and String Parameter

我有一個這樣的界面

public interface IPrice
{
    IEnumerable<Price> GetPrice(string portalShopName);

    IEnumerable<Price> GetPrice(DateTime? lastRunDate);

}

在這種情況下,我如何使用可為空的DateTime訪問第二種方法

正如PetSerAl在評論中所述,您可以像這樣進行投射

  IPrice price = ...

  var result = price.GetPrice((DateTime?)null);

但是,我建議實現一種擴展方法隱藏這種類型轉換:

  public static class PriceExtensions {
    //TODO: may be "GetDefaultPrice" is a better name for the method
    public static IEnumerable<Price> GetPrice(this IPrice price) {
      if (null == price)
        throw new ArgumentNullException("price");

      return price.GetPrice((DateTime?)null);
    }
  }

所以你可以把它

  IPrice price = ...

  var result = price.GetPrice();

您應該首先在這樣的類中實現接口:

public class testClass : IPrice
{

    public IEnumerable<Price> GetPrice(string portalShopName)
    {
        throw new NotImplementedException();
    }

    public IEnumerable<Price> GetPrice(DateTime? lastRunDate)
    {
        throw new NotImplementedException();
    }
}

然后,您可以GetPrice以下方式調用GetPrice

testClass tst = new testClass();
tst.GetPrice((DateTime?)null);
tst.GetPrice((string) null);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM