比如我有如下两个对应类型的方法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>();
}
目前可以实现吗?
如果不可以,有什么可实现的代替方式吗?
{
///
}
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>();
}
目前可以实现吗?
如果不可以,有什么可实现的代替方式吗?
ValueTypeMethod<TV>() where TV: structClassTypeMethod<TC>() where TC: class,new()
增加约束了。
那么CommonTypeMethod<T> 肯定没发又是struct又是class
假设你不指定,那么编译器也没办法知道T到底什么类型。就更加没办法调用了。
除非你把where约束去掉。
{
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");
}