簡體   English   中英

關於方法重載的建議

[英]Advice on Method overloads

請參閱以下方法。

    public static ProductsCollection GetDummyData(int? customerId, int? supplierId)
    {
        try
        {
            if (customerId != null && customerId > 0)
            {
                Filter.Add(Customres.CustomerId == customerId);
            }

            if (supplierId != null && supplierId > 0)
            {
                Filter.Add(Suppliers.SupplierId == supplierId);
            }

            ProductsCollection products = new ProductsCollection();

            products.FetchData(Filter);

            return products;
        }
        catch
        {
            throw;
        }
    }

    public static ProductsCollection GetDummyData(int? customerId)
    {
        return ProductsCollection GetDummyData(customerId, (int?)null);
    }

    public static ProductsCollection GetDummyData()
    {
        return ProductsCollection GetDummyData((int?)null);
    }

1-請告知我如何對CustomerId和SupplierId都進行重載,因為只能使用GetDummyData(int?)創建一個重載。 我是否應該添加另一個參數來提及第一個參數是CustomerId或SupplierId,例如GetDummyData(int ?, string)。 或者我應該使用enum作為第二個參數,並提到第一個參數是CustoemId或SupplierId。

2-這個條件是正確的還是只是檢查> 0是否足夠->如果(customerId!= null && customerId> 0)

3-像這樣使用Try / catch是正確的嗎?

4-傳遞(int?)null是正確的或任何其他更好的方法。

編輯:

我發現了其他類似的帖子,因為我不了解泛型,所以才遇到這個問題。 我對嗎? 以下是帖子。

重載方法調用重載方法

  1. 為什么不創建單獨的GetCustomerData(int)GetSupplierData(int)方法? (如果需要,還可以使用GetData()GetData(int,int) 。)

  2. 如果將方法參數更改為int而不是int? 那么您只需要(自行決定)檢查它們是否大於0。

  3. 在這種情況下,不需要try...catch 如果您正在做的只是重新拋出異常,那么就不要一開始就抓住它。

  4. 請參閱上面的1和2。

編輯:也許像這樣...

public static ProductsCollection GetData()
{
    return GetDataImpl(-1, -1);
}

public static ProductsCollection GetData(int customerId, int supplierId)
{
    if (customerId <= 0)
        throw new ArgumentOutOfRangeException("customerId");

    if (supplierId <= 0)
        throw new ArgumentOutOfRangeException("supplierId");

    return GetDataImpl(customerId, supplierId);
}

public static ProductsCollection GetCustomerData(int customerId)
{
    if (customerId <= 0)
        throw new ArgumentOutOfRangeException("customerId");

    return GetDataImpl(customerId, -1);
}

public static ProductsCollection GetSupplierData(int supplierId)
{
    if (supplierId <= 0)
        throw new ArgumentOutOfRangeException("supplierId");

    return GetDataImpl(-1, supplierId);
}

private static ProductsCollection GetDataImpl(int customerId, int supplierId)
{
    if (customerId > 0)
        Filter.Add(Customers.CustomerId == customerId);

    if (supplierId > 0)
        Filter.Add(Suppliers.SupplierId == supplierId);

    ProductsCollection products = new ProductsCollection();
    products.FetchData(Filter);

    return products;
}

您對try catch沒有做任何事情,所以為什么要包含它。 無論如何,您的例外都會冒泡到調用方法,因此只需刪除多余的try catch代碼。

我將放棄第二種和第三種方法,因為它們實際上沒有做任何事情。 除非您有任何保留它們的理由,例如它們是舊代碼,否則我將其刪除。 這只會使代碼變得更加復雜,以供將來支持。

暫無
暫無

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

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