Restricting T to string and int?

前端 未结 7 1459
悲哀的现实
悲哀的现实 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<T>
    {
        protected MyRestrictedGeneric() { }
    
    
        // Create the right class depending on type T
        public static MyRestrictedGeneric<T> Create<T>()
        {
            if (typeof(T) == typeof(string))
                return new StringImpl() as MyRestrictedGeneric<T>;
    
            if (typeof(T) == typeof(int))
                return new IntImpl() as MyRestrictedGeneric<T>;
    
            throw new InvalidOperationException("Type not supported");
        }
    
    
        // The specialized implementation are protected away
        protected class StringImpl : MyRestrictedGeneric<string> { }
        protected class IntImpl : MyRestrictedGeneric<int> { }
    }
    

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

    0 讨论(0)
提交回复
热议问题