What does “where T : somevalue” mean?

前端 未结 4 1257
暖寄归人
暖寄归人 2021-02-05 22:14

What does where T : somevalue mean? I just saw some code that said where T : Attribute. I think this has something to do with generics but I am not sur

4条回答
  •  臣服心动
    2021-02-05 22:34

    The where clause is used to limit the arguments that can be passed when using generics. When you create a generic class it might be in your best interest to specify an argument type depending on how you plan to use T in your class. If it anything besides what System.Object can do then it is probably best to use a constraint as you will get a compile time error vs a runtime.

    example

    If you create a class

    class Person where T : System.IComparable
    {
       //can now use CompareTo
    }
    

    You can not not pass this class anything that does not implement IComparable. So it is now safe to use CompareTo on anything that is passed into the the Person class.

提交回复
热议问题