我有两个类:Superclass和派生Subclass:Superclass。我有一个通用的方法:
public void DoSmth<T>(T obj)
where T : Superclass
{
if(typeof(T).IsSubclassOf(typeof(Subclass))
{
DoSmth2<T>(obj);
}
//...
}
public void DoSmth2<T>(T obj)
where T : Subclass
{
//...
}
如您所见,我想从Superclass的泛型方法调用Subclass的泛型方法。但是编译器说我做不到:
The type 'T' cannot be used as type parameter
'T' in the generic type or method 'DoSmth2<T>(T)'.
There is no implicit reference conversion from 'T' to 'Subclass'
我使用.Net 3.5。我明白我不能像上面写的那样那样做但是有什么方法可以做到吗?
答案 0 :(得分:3)
你不能,但你不必。
public void DoSmth<T>(T obj)
where T : Superclass
{
//untested but something like this
Subclass obj2 = (obj as Subclass);
if(obj2 != null)
{
DoSmth2(obj2);
}
//...
}