繁体   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