首页 > 代码库 > Generics

Generics

Geniric helps to reuse the methods which avoid overloading methods that will become hard to maintain

Public Class Equalizer{    public bool compare (string s1, string s2)     {return s1 == s2;}    public bool compare (int i1, int i2)    {return i1 == i2;}}

If we have a need to add a cross cutting aspect to all compare method like logging, how would current design accomodate the need

技术分享
Public Class EqualizerWithLogging{    public bool compare (string s1, string s2)     {        iLoogger.log(XXXX);       return s1 == s2;     }    public bool compare (int i1, int i2)    {       iLoogger.log(XXXX);return i1 == i2;}}
View Code

By simply resort this to generic class can resolve this issue

Public Class EqualizerWithLogging <T>{    public bool compare (T s1, T s2)     {        iLoogger.log(XXXX);       return s1 == s2;     }}

 

  

Generics