泛型方法 中使用 值类型

        static void StringTarget(string arg)
        {
            Console.WriteLine("arg in uppercase is: {0}", arg.ToUpper());
        }

        static void IntTarget(int arg)
        {
            Console.WriteLine("++arg is: {0}", ++arg);
        }

        static void GenericTarget<T>(T arg)
        {
            if (arg is string)
            {
                StringTarget(arg as string);
            }

            if (arg is int)
            {
                IntTarget((int)(arg as ValueType));
            }
        }

泛型中值类型的转换是个很恶心的事情。直接使用 as 会有以下的 编译错误提示

还有个老井给了个如下的代码来处理

 

public class MyClass<T>
{
 ...
}

public class IntClass : MyClass<int>
{
  public void IncrementMe()
  {
    this.value++;
  }
}

但是我这里对方法是没有办法重写的所以只有用 as 转成 valueType 再强制转换了,但愿没有box 和 unbox 的性能损失。

 

posted @ 2012-06-07 12:31  默蛇  阅读(277)  评论(0编辑  收藏  举报