声明一个带泛型的类:    public class Ttext<T>
    {
        public T Add(T arg)
        {
            //请问这里如何对参数arg的值进行读取和运算?
        }
    }
问题一:Ttext类的泛型<T>,如何限定只能接受double, int, 或string问题二:在public T Add(T arg),如何读取参数arg的值并进行运算?
(总不会使用switch(typeof(arg))吧!那样的话,泛型的优势何在?谢谢!

解决方案 »

  1.   

    泛型集合中的<T>是obj类型
    限定 用实例啊  list<double>   list<int>   list<string> 
            public T Add(T arg) 
            {
                在这里 直接使用传进来的参数 rag进行运算
             }
      

  2.   

    public class Ttext<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
    {
        // Fields
        private const int _defaultCapacity = 4;
        private T[] _items;
     
        private int _version;public Ttext()
    {
    _items=new T[_defaultCapacity];
    }        public T Add(T arg)
            {
                this._items[this._size++] = item;
        this._version++;        }
        }
    }
      

  3.   

    其实这种集合涉及到的东西还是很多的,主要是在内部有一个T[]这样的数组,调用Add(T t)时是给数组中的元素赋值,当然需要判断数组中的元素是否已经全部赋值,如果是就需要重新实例化一个数组,将原数组的数据复制到新数组中去,然后再进行赋值。
      

  4.   


    "读取和运算"什么呢?当你用过于空洞以至于一点具体实际功能都没有的东西来问,就根本不可能有解答。没有什么“标准”的解决办法,否则就不会有“重构”这种概念。你只有明确了你的需求,才能有合适的解答。如果解答不合适,你首先要扪心自问你提的问题到底有没有说明白?当一个人开发软件是,他为什么要使用泛型,闲的吗?他为什么不可一写成这样?        public class Ttext
            {
                public int Add(int arg)
                {
                    throw new Exception("没有实质设计内容");
                }
                public string Add(string arg)
                {
                    throw new Exception("没有实质设计内容");
                }
                public double Add(double arg)
                {
                    throw new Exception("没有实质设计内容");
                }
            }
    只要很好地完成任务,被很简单清晰地调用,就是好的设计。你一定认为这根本没有解决你的千变万化的需求。可是你的需求中实用的东西到底在哪里呢?没有说清楚。