Maybe my question is simple or just stupid but I have following problem:
I have 2 polymorphic methods:
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:
ClientService.Index(Alias, items.ToList());
Always the method Index<T>(string alias, T item)
is getting called. 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
. 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
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
.
Your two options are
您可以指定通用参数类型,例如
ClientService.Index<Item>(Alias, items.ToList());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.