Restricting T to string and int?

前端 未结 7 1464
悲哀的现实
悲哀的现实 2020-12-16 12:17

I have built myself a generic collection class which is defined like this.

public class StatisticItemHits{...}

This class can be

7条回答
  •  一生所求
    2020-12-16 12:53

    Given that you only have two types here I would go down an OO route here instead and just have two classes for the two types.

    Generics are best used where the circumstances in which they can be applied are, you know, generic. They're a lot less use in circumstances like this.

    You can restrict to struct or class types only, and I do think that there need to be numeric or operator based restrictions (e.g. must support +=)

    Int and string are really quite different, certainly more different than int and double. It wouldn't make much sense for a generic class to support the immutable reference type of string and the value type of int without also supporting other types more similar to either of them.

提交回复
热议问题