In c# what does 'where T : class' mean?

前端 未结 10 1973
太阳男子
太阳男子 2020-11-29 18:53

In C# what does where T : class mean?

Ie.

public IList DoThis() where T : class
10条回答
  •  迷失自我
    2020-11-29 19:18

    where T: class literally means that T has to be a class. It can be any reference type. Now whenever any code calls your DoThis() method it must provide a class to replace T. For example if I were to call your DoThis() method then I will have to call it like following:

    DoThis();
    

    If your metthod is like like the following:

    public IList DoThis() where T : class
    {
       T variablename = new T();
    
       // other uses of T as a type
    
    }
    

    Then where ever T appears in your method, it will be replaced by MyClass. So the final method that the compiler calls , will look like the following:

    public IList DoThis() 
    {
       MyClass variablename= new MyClass();
    
      //other uses of MyClass as a type
    
      // all occurences of T will similarly be replace by MyClass
     }
    

提交回复
热议问题