我知道有非常相似的问题,但我不确定它们中的任何一个正是我需要的。我有2个方法做同样的事情(所以我不需要覆盖或任何东西)唯一的区别是参数和返回类型。
public List<List<TestResult>> BatchResultsList(List<TestResult> objectList)
{
}
public List<List<ResultLinks>> BatchResultsList(List<ResultLinks> objectList)
{
}
是否有一种巧妙的方法,不涉及重复代码(类型在方法中使用)。
答案 0 :(得分:6)
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。然后:
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
}
}
当你调用方法时,你当然可以省略type参数,因为可以推断出来:
List<TestResult> objectList = new List<TestResult>();
List<List<TestResult>> list = BatchResultsList(objectList);
答案 1 :(得分:2)
public List<List<T>> BatchResultsList<T>(List<T> objectList)
{
}
当你为TestResult调用它时:
BatchResultsList<TestResult>(testResultList)
for ResultLinks:
BatchResultsList<ResultLinks>(resultLinksList)
我认为因为你的2个方法,TestResult&amp; ResultLinks必须实现一个通用接口,我们称之为SomeInterface&amp;一个常见的构造函数,让我们选择无参数构造函数:
你会声明并使用这样的方法:
public List<List<T>> BatchResultsList<T>(List<T> objectList)
where T:SomeInterface, new()
{
List<List<T>> toReturn = new List<List<T>>();
//to instantiate a new T:
T t = new T();
foreach (T result in objectList)
{
//use result like a SomeInterface instance
}
//...
return toReturn;
}
答案 2 :(得分:1)
怎么样
public List<IList> BatchResultsList(List<IList> objectList)
{
}
答案 3 :(得分:0)
通用版本:
public List<List<T>> BatchResultsList<T>(List<T> objectList){}