Extension methods on a struct

前端 未结 4 429
野趣味
野趣味 2020-12-17 07:46

Can you add extension methods to a struct?

4条回答
  •  执念已碎
    2020-12-17 08:33

    For future Googlers (and Bingers), here's some code to extend a struct. This example turns the value into a double type.

    public static class ExtensionMethods {
    
       public static double ToDouble(this T value) where T : struct {
          return Convert.ToDouble(value);
       }
    }
    

    After this you can use ToDouble() like you use ToString(). Be careful on conversion items like overflows.

提交回复
热议问题