Uses for static generic classes?

前端 未结 9 1778
猫巷女王i
猫巷女王i 2020-12-08 10:11

What are the key uses of a Static Generic Class in C#? When should they be used? What examples best illustrate their usage?

e.g.

         


        
9条回答
  •  孤街浪徒
    2020-12-08 10:49

    One use of static generic classes that I recently learned was possible is to define a constraint on the class level for the type, then the constraint applies to all the static members of the class, what I also learned is that this is not allowed for static generic classes that define extention methods.

    For example if you are going to create a static generic class and you know all the generic types should be IComparable (just an example) then you can do the following.

    static class MyClass where T : IComparable
    {
      public static void DoSomething(T a, T b)
      {
      }
    
      public static void DoSomethingElse(T a, T b)
      {
      }
    }
    

    Notice that I did not need to apply the constraint to all the member, but just at the class level.

提交回复
热议问题