代码之家  ›  专栏  ›  技术社区  ›  xoxo

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

  •  0
  • xoxo  · 技术社区  · 16 年前

    我知道有非常相似的问题,但我不确定它们是否正是我需要的。我有两个方法可以做完全相同的事情(所以我不需要重写或做任何事情),唯一的区别是参数和返回类型。

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

    是否有一种简单的方法可以做到这一点,而不涉及重复代码(类型在方法内部使用)。

    4 回复  |  直到 16 年前
        1
  •  6
  •   Rytmis    16 年前
    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的类型,以便只处理特定种类的对象,那么可以让testreult和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
        }
    }
    

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

    List<TestResult> objectList = new List<TestResult>();
    List<List<TestResult>> list = BatchResultsList(objectList);
    
        2
  •  2
  •   manji    16 年前

    使用 generic methods

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

    当您为测试结果调用它时:

    BatchResultsList<TestResult>(testResultList)
    

    对于结果链接:

    BatchResultsList<ResultLinks>(resultLinksList)
    

    编辑:

    我假定,由于这是两个方法中的相同代码,因此testsult&resultlinks必须实现一个公共接口,让我们称之为someinterface&a公共构造函数,让我们选择一个无参数的接口:

    您将声明并使用如下方法:

        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;
        }
    
        3
  •  1
  •   twk    16 年前

    怎么样

    public List<IList> BatchResultsList(List<IList> objectList)
    {
    }
    
        4
  •  0
  •   Vitaliy Liptchinsky    16 年前

    通用版本:

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