簡體   English   中英

C#中返回類型多於1的函數是否可行?

[英]Are functions with more than 1 return types in C# possible?

我知道函數本身不能有超過1種返回類型。 我正在尋找其他選擇。

腳本

我有一個Product類,我有各種屬性。 我有一個Discounts類,其中我有很多其他課程 (不同類型的折扣)

折扣,無論類型如何,都是對象 - 因為它們都具有Type (百分比/固定)和Value (十進制格式的價格)等。每個折扣也有一個分配給它的產品,以便系統知道哪個要應用此折扣規則的產品。

三種折扣類型:

BasicDiscount AdvancedDiscount SuperDiscount

我為每個不同的折扣都有一個List<T> ,因此它們按類型分組。

我的目標是有一個函數將Product作為參數,並循環遍歷折扣列表中的每個折扣以檢查產品是否存在。 如果找到對象,我希望函數返回該對象,無論是BasicDiscountAdvancedDiscountSuperDiscount等。(列出的折扣類型將是我的折扣類中的折扣)

這是我目前所處位置的一個例子。

假設Product X有一個BasicDiscount

function object getDiscount(Product p){

    (UnknownType) discount;

     foreach (BasicDiscount b in BasicDiscounts)
                    if (b.Product.ID == p.ID)
                       discount = b;
     foreach (AdvancedDiscount ad in AdvancedDiscounts)
                    if (ad.Product.ID == p.ID)
                       discount = ad;
     foreach (SuperDiscount sd in SuperDiscounts)
                    if (sd.Product.ID == p.ID)
                       discount = sd;

     return discount;

}

由於我不知道該產品可能存在哪種類型的折扣,我該如何才能返回正確的折扣?

或者還有另一種方式嗎?

TLDR; - 如果你必須創建一個函數,其中必須返回名稱或年齡(使用int或string作為其數據類型),但你不知道將選擇哪一個 - 你的函數會返回什么樣的返回類型是?

非常感謝幫助,謝謝! :)

接口!

您可以使用每個折扣類實現的接口,然后您可以將接口返回到調用方法。

例如。

public interface IDiscount
{
    // method or property signatures
}

public class BasicDiscount : IDiscount
{
    // implementation of interface members
}

public IDiscount getDiscount(Product p)
{
     (IDiscount) discount;

     foreach (BasicDiscount b in BasicDiscounts)
         if (b.Product.ID == p.ID)
             discount = b;
     foreach (AdvancedDiscount ad in AdvancedDiscounts)
         if (ad.Product.ID == p.ID)
             discount = ad;
     foreach (SuperDiscount sd in SuperDiscounts)
         if (sd.Product.ID == p.ID)
             discount = sd;

     return discount;
}

暫無
暫無

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

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