Restricting T to string and int?

前端 未结 7 1469
悲哀的现实
悲哀的现实 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 13:18

    You cannot restrict it to string and int from the where clause. You can check it in the constructor, but that is probably not a good place to be checking. My approach would be to specialize the class and abstract the class creation into a (semi-)factory pattern:

    class MyRestrictedGeneric
    {
        protected MyRestrictedGeneric() { }
    
    
        // Create the right class depending on type T
        public static MyRestrictedGeneric Create()
        {
            if (typeof(T) == typeof(string))
                return new StringImpl() as MyRestrictedGeneric;
    
            if (typeof(T) == typeof(int))
                return new IntImpl() as MyRestrictedGeneric;
    
            throw new InvalidOperationException("Type not supported");
        }
    
    
        // The specialized implementation are protected away
        protected class StringImpl : MyRestrictedGeneric { }
        protected class IntImpl : MyRestrictedGeneric { }
    }
    

    This way you can limit the class's usage to just string and int internally inside your class.

提交回复
热议问题