使用不同参数类型的相同方法? [英] Same method that takes a different parameter type?
问题描述
我知道有非常相似的问题,但是我不确定它们中的任何一个正是我所需要的.我有2种方法做完全相同的事情(因此我不需要重写或做任何事情),唯一的区别是参数和返回类型.
I know there are very similar questions but im not sure that any of them are exactly what i need. I have 2 methods that do exactly the same thing (so i dont need to override or anything) the only difference is the parameter and return types.
public List<List<TestResult>> BatchResultsList(List<TestResult> objectList)
{
}
public List<List<ResultLinks>> BatchResultsList(List<ResultLinks> objectList)
{
}
是否有一种整齐的方法可以完成此过程,而无需重复代码(类型在方法内部使用).
is there a neat way of doing this that doesnt involve duplciate code (the types are used inside the method).
推荐答案
public List<List<T>> BatchResultsList<T>(List<T> objectList)
{
foreach(T t in objectList)
{
// do something with T.
// note that since the type of T isn't constrained, the compiler can't
// tell what properties and methods it has, so you can't do much with it
// except add it to a collection or compare it to another object.
}
}
,如果您需要限制T的类型,以便仅处理特定种类的对象,则使TestResult和ResultLinks都实现一个接口,例如IResult.然后:
and if you need to limit the type of T so that you'll only process specific sorts of objects, make both TestResult and ResultLinks implement an interface, say, IResult. Then:
public interface IResult
{
void DoSomething();
}
public class TestResult : IResult { ... }
public class ResultLinks : IResult { ... }
public List<List<T>> BatchResultsList<T>(List<T> objectList) where T : IResult
{
foreach(T t in objectList)
{
t.DoSomething();
// do something with T.
// note that since the type of T is constrained to types that implement
// IResult, you can access all properties and methods defined in IResult
// on the object t here
}
}
调用该方法时,由于可以推断出类型参数,因此当然可以省略它:
When you call the method, you can of course omit the type parameter, since it can be inferred:
List<TestResult> objectList = new List<TestResult>();
List<List<TestResult>> list = BatchResultsList(objectList);
这篇关于使用不同参数类型的相同方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!