簡體   English   中英

具有泛型類型和列表的C#多態

[英]C# polymorphism with generic type and list

也許我的問題很簡單,或者只是愚蠢,但我有以下問題:

我有2種多態方法:

public void Index<T>(string alias, IEnumerable<T> items) where T : class
{
    var result = Client.IndexMany(items, alias);
    ExceptionHandling(result);
}

public void Index<T>(string alias, T item) where T : class
{
    var result = Client.Index(item, x => x.Index(alias));
    ExceptionHandling(result);
}

當我現在嘗試使用以下命令調用獲取List的方法時:

ClientService.Index(Alias, items.ToList());

總會調用方法Index<T>(string alias, T item) 如何更改列表調用第一個方法,單個對象調用第二個方法呢?

我有替代解決方案!

您可以使用參數名稱來區分重載!

您會看到,第一個重載的第二個參數稱為items ,而第二個重載的第二個參數稱為item 因此,如果要調用第一個重載,則只需要:

ClientService.Index(Alias, items: items.ToList());

如果要第二個,您可以致電:

ClientService.Index(Alias, item: items.ToList());

看到不同?

干凈整潔! 在chsarppad上測試: http ://csharppad.com/gist/0d7f71c66079fefa680ea3f6afb2ed63

這是一個方法的名稱相同的問題(重載),其中兩個重載顯然會執行不同的操作-您有解決方案的提示; 在其他地方,您已將下游方法命名為IndexIndexMany

您的兩個選擇是

  1. 分別命名方法並適當
  2. 使用AsEnumerable()擴展方法將列表顯式轉換為IEnumerable<T>

您可以指定通用參數類型,例如

ClientService.Index<Item>(Alias, items.ToList());

暫無
暫無

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

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