C# Generics and polymorphism: an oxymoron?

前端 未结 6 1613
日久生厌
日久生厌 2020-12-16 12:17

I just want to confirm what I\'ve understood about Generics in C#. This has come up in a couple code bases I\'ve worked in where a generic base class is used to create type

6条回答
  •  庸人自扰
    2020-12-16 12:54

    As far as I can see, consuming code doesn't need specifics of generic class (i.e., it doesn't depends on what T is). So, why don't you introduce interface that SomeClass will implement, and use instance of this interface.

    E.g.:

    public interface ISome
    {
        void SomeMethod();
    }
    
    public class SomeClass: ISome
    {
        public virtual void SomeMethod(){ }
    }
    
    public void DoSomethingClienty()
    {
        Factory factory = new Factory();
        ISome someInstance = factory.Create();
    
        someInstance.SomeMethod();
    }
    

    Now, subclasses of SomeClass can operate differently on different Ts, but consuming code won't change.

提交回复
热议问题