[英]C# defining one method for different types of argument
I've seen that you can define different functions for different sets of arguments in c#, like so: 我已经看到您可以为c#中的不同参数集定义不同的函数,如下所示:
public bool foo(string bar) {
//do something1
}
public bool foo(int bar, bool spam) {
//do something2
}
But can you make a single function definition for different sets of arguments? 但是可以为不同的参数集创建一个函数定义吗? In my case, it'll be for
IList
and List
. 就我而言,它将用于
IList
和List
。 Since those types are only slightly varied I can use the same function for both IList
and List
objects (it's a simple function that just looks for some specific element). 由于这些类型仅略有不同,因此我可以对
IList
和List
对象使用相同的函数(这是一个简单的函数,仅查找某些特定元素)。 Is there any clever way of doing this, as in not a copypasta? 是否有任何聪明的方法可以做到这一点,例如不是复制粘贴?
Thanks! 谢谢!
Yeah, you could use only IList
as the type of your parameter, since List
implements IList
. 是的,您只能使用
IList
作为参数类型,因为List
实现了IList
。
For instance, you could declare 例如,您可以声明
public void MethodName(IList list)
{
// Method's body.
}
and the list you will pass could be either a concrete List
or a type that implements IList
, without having to declare two mehods. 并且您将传递的列表可以是具体的
List
或实现IList
的类型,而无需声明两个方法。
Well if you are trying to use IList
and List
. 好吧,如果您尝试使用
IList
和List
。 I don't think you need different methods for that. 我认为您不需要其他方法。 Because
List
implements IList
and thus you can easily cast them in your code. 由于
List
实现了IList
,因此您可以轻松地将它们IList
代码。 So the same functions will work for both. 因此,相同的功能将对两者都起作用。
And if you are not modifying the items in the function then you can go little further and use IEnumerable
as the parameter type. 而且,如果您不修改函数中的项目,则可以更进一步,将
IEnumerable
用作参数类型。
such as - 如 -
protected void Method(IList list){
}
or 要么
protected void Method(IEnumerable items){
}
But remember, there is a difference when using interfaces, they are passed by references and thus no new copy is created. 但是请记住,使用接口时会有所不同,它们由引用传递,因此不会创建新副本。 Any modification you make will affect the original item collection.
您所做的任何修改都会影响原始的项目集合。 If you need to pass by value or want to create a new copy call
.ToList()
inside - 如果您需要按值传递或要在内部创建新的复制调用
.ToList()
-
such as - 如 -
protected void Method(IList list){
//some code
var copied = list.ToList();
}
or 要么
protected void Method(IEnumerable items){
//some code
var copied = items.ToList();
}
List object internally inherited by IList. IList内部继承的列表对象。 So use when you call method then convert IList to List object or List object to IList what ever you use object type in method.
因此,无论您在方法中使用哪种对象类型,都可以在调用方法时将IList转换为List对象或将List对象转换为IList。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.