Practical advantage of generics vs interfaces

前端 未结 8 1533
梦毁少年i
梦毁少年i 2020-11-29 02:35

What would be a practical advantage of using generics vs interfaces in this case:

void MyMethod(IFoo f) 
{
}

void MyMethod(T f) : where T : IFoo
{
         


        
8条回答
  •  孤城傲影
    2020-11-29 03:33

    In this particular case, there is no benefit. In general you wouldn't specify this at a method level, but at a class level. E.g.,

    public interface IFoo {
            void DoSomethingImportant();
        }
    
        public class MyContainer where T : IFoo {
            public void Add(T something){
                something.DoSomethingImportant();
                AddThisThing(something);
            }
    
            public T Get() {
                T theThing = GetSomeKindOfThing();
                return theThing;
            }
        }
    

    Notice that we require T to implement IFoo because of the Add method where we need to call the DoSomethingImportantMethod implemented by IFoo.

    But notice in the Get method that we will return the T provided by end user of this class instead of a plain old IFoo, which alleviates the need for the developer to always cast to their actual concrete T.

    Example:

    public class Bar : IFoo{
      //....
    }
    
    MyContainer m = new MyContainer();
    //stuff happens here
    Bar b = m.Get();
    

    Note that if I was just returning an IFoo, then I would have to do this at the last line instead:

    Bar b = (Bar) m.Get();
    

提交回复
热议问题