Difference between interface as type constraint and interface as parameter?

前端 未结 5 1367
暖寄归人
暖寄归人 2021-02-13 14:30

If I wanted to create a method that takes an instance of IList as a parameter (or any other interface, but let\'s use IList as an example), I could cre

5条回答
  •  眼角桃花
    2021-02-13 14:54

    Reagrding your example I would prefer the second approach. Generic methods or classes are mostly used when the caller can use them with more than on type as in your example. In this case you can avoid a base class (e.g. object) as return value and provide type safe return values. On simple sample

    public class Foo
    {
        public T GetSomething()
        {
            return default(T);
        }
    }
    

提交回复
热议问题