比如我有如下两个对应类型的方法public void ValueTypeMethod<TV>() where TV: struct
{
   ///
}
public void ClassTypeMethod<TC>() where TC: class,new()
{
   ///
}
然后我有一个无约束的泛型方法,我希望可以在里面根据情况不同调用上面两个方法
public void CommonTypeMethod<T>()
{
    if(typeof(T).IsValueType)
        ValueTypeMethod<T>();
    else if (typeof(T).IsClass)
        ClassTypeMethod<T>();
}
目前可以实现吗?
如果不可以,有什么可实现的代替方式吗?

解决方案 »

  1.   

    不行啊,你都在
    ValueTypeMethod<TV>() where TV: structClassTypeMethod<TC>() where TC: class,new()
    增加约束了。
    那么CommonTypeMethod<T>  肯定没发又是struct又是class
    假设你不指定,那么编译器也没办法知道T到底什么类型。就更加没办法调用了。
    除非你把where约束去掉。
      

  2.   

    static void Main(string[] args)
            {
                CommonTypeMethod<int>();
                CommonTypeMethod<User>();            Console.ReadLine();
            }        public static void CommonTypeMethod<T>()
            {
                if (typeof(T).IsValueType)
                    ValueTypeMethod<T>();
                else if (typeof(T).IsClass)
                    ClassTypeMethod<T>();
            }        public static void ValueTypeMethod<TV>()
            {
                Console.WriteLine("ValueType");
            }
            public static void ClassTypeMethod<TC>()
            {
                Console.WriteLine("ClassType");
            }
      

  3.   

    单就public void CommonTypeMethod<T>()这类定义来说,它有什么内外交互的内涵呢?内涵越少则外延越大,大到根本不落地的时候就产生内耗了,就成了 bug。你至少要有输入、或者输出,才应该写 <T> 这种东西。