interface as argument or generic method with where - what is the difference?

前端 未结 4 1537
灰色年华
灰色年华 2021-01-17 11:46

Is any difference between :

public void Method1(class1 c, T obj) where T:Imyinterface

And

public void Method2(clas         


        
4条回答
  •  日久生厌
    2021-01-17 12:24

    Using a generic method gives you various possibilities with slight signature changes:

    1. public void Method1(class1 c, T obj) where T:Imyinterface, new():
      This allows to instantiate new instances of type T.
    2. public T Method1(class1 c, T obj) where T:Imyinterface:
      This allows you to use the method without casting it's return value when needed.
    3. public void Method1(class1 c, ref T obj) where T:Imyinterface:
      This allows you to assing a new value to obj's reference. Same applies to out.

    These are impossible with the non generic version.

提交回复
热议问题