简体   繁体   English

具有泛型类型和列表的C#多态

[英]C# polymorphism with generic type and list

Maybe my question is simple or just stupid but I have following problem: 也许我的问题很简单,或者只是愚蠢,但我有以下问题:

I have 2 polymorphic methods: 我有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);
}

When I'm now trying to call the method which is getting a List with following command: 当我现在尝试使用以下命令调用获取List的方法时:

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

Always the method Index<T>(string alias, T item) is getting called. 总会调用方法Index<T>(string alias, T item) How can I change it that Lists call the first Method and single objects call the second Method? 如何更改列表调用第一个方法,单个对象调用第二个方法呢?

I have an alternative solution! 我有替代解决方案!

You can use parameter names to differentiate the overloads! 您可以使用参数名称来区分重载!

You see, the first overload's second parameter is called items , whereas the second overload's second parameter is called item . 您会看到,第一个重载的第二个参数称为items ,而第二个重载的第二个参数称为item Therefore, if you want to call the first overload, you just need: 因此,如果要调用第一个重载,则只需要:

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

If you want the second instead, you can call: 如果要第二个,您可以致电:

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

See the difference? 看到不同?

Clean and tidy! 干净整洁! Tested on chsarppad: http://csharppad.com/gist/0d7f71c66079fefa680ea3f6afb2ed63 在chsarppad上测试: http ://csharppad.com/gist/0d7f71c66079fefa680ea3f6afb2ed63

This is the problem with having the same name for a method (overloading) where the two overloads clearly do different things - you have a hint to the solution; 这是一个方法的名称相同的问题(重载),其中两个重载显然会执行不同的操作-您有解决方案的提示; elsewhere you have named the downstream methods Index and IndexMany . 在其他地方,您已将下游方法命名为IndexIndexMany

Your two options are 您的两个选择是

  1. Name the methods differently, and appropriately 分别命名方法并适当
  2. Explicitly cast your list to an IEnumerable<T> using AsEnumerable() extension method. 使用AsEnumerable()扩展方法将列表显式转换为IEnumerable<T>

您可以指定通用参数类型,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM