采用不同参数类型的相同方法?

xox*_*oxo 0 c# generics methods

我知道有非常相似的问题,但我不确定它们中的任何一个正是我需要的.我有2个方法做完全相同的事情(所以我不需要覆盖或任何东西)唯一的区别是参数和返回类型.

public List<List<TestResult>> BatchResultsList(List<TestResult> objectList)
    {

    }

public List<List<ResultLinks>> BatchResultsList(List<ResultLinks> objectList)
    {

    }
Run Code Online (Sandbox Code Playgroud)

有没有一种巧妙的方法,这不涉及duplciate代码(类型在方法内使用).

Ryt*_*mis 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你需要限制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
    }
}
Run Code Online (Sandbox Code Playgroud)

当您调用该方法时,您当然可以省略type参数,因为可以推断出:

List<TestResult> objectList = new List<TestResult>();
List<List<TestResult>> list = BatchResultsList(objectList);
Run Code Online (Sandbox Code Playgroud)