Is there a constraint that restricts my generic method to numeric types?

后端 未结 21 2594
栀梦
栀梦 2020-11-21 05:48

Can anyone tell me if there is a way with generics to limit a generic type argument T to only:

  • Int16
  • Int32
21条回答
  •  感情败类
    2020-11-21 06:31

    I had a similar situation where I needed to handle numeric types and strings; seems a bit of a bizarre mix but there you go.

    Again, like many people I looked at constraints and came up with a bunch of interfaces that it had to support. However, a) it wasn't 100% watertight and b), anyone new looking at this long list of constraints would be immediately very confused.

    So, my approach was to put all my logic into a generic method with no constraints, but to make that generic method private. I then exposed it with public methods, one explicitly handling the type I wanted to handle - to my mind, the code is clean and explicit, e.g.

    public static string DoSomething(this int input, ...) => DoSomethingHelper(input, ...);
    public static string DoSomething(this decimal input, ...) => DoSomethingHelper(input, ...);
    public static string DoSomething(this double input, ...) => DoSomethingHelper(input, ...);
    public static string DoSomething(this string input, ...) => DoSomethingHelper(input, ...);
    
    private static string DoSomethingHelper(this T input, ....)
    {
        // complex logic
    }
    

提交回复
热议问题