English 中文(简体)
采用不同参数类型的方法?
原标题:Same method that takes a different parameter type?
  • 时间:2009-10-13 08:16:21
  •  标签:

我知道存在非常相似的问题,但不能肯定,这些问题中的任何问题完全是需要的。 我有两种方法完全相同(即表面上需要凌驾于任何东西),唯一的区别是参数和返回类型。

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

    }

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

    }

这样做的方法有点模糊(在方法中使用)。

最佳回答
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型号,以便你只处理特定种类的物体,使测试结果和结果链接能够使用一个接口,例如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
    }
}

在你称之为这一方法时,你当然可以忽略这种参数,因为可以推断:

List<TestResult> objectList = new List<TestResult>();
List<List<TestResult>> list = BatchResultsList(objectList);
问题回答

内容

public List<IList> BatchResultsList(List<IList> objectList)
{
}

通用文本:

public List<List<T>> BatchResultsList<T>(List<T> objectList){}




相关问题
热门标签