【问题标题】:Call generic method for subclass from generic method for superclass从超类的泛型方法调用子类的泛型方法
【发布时间】:2012-04-21 18:31:01
【问题描述】:

我有两个类:超类和派生的子类:超类。我有一个通用方法:

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
{ 
    //... 
}

如您所见,我想从超类的泛型方法调用子类的泛型方法。但是编译器说我不能这样做:

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。我知道我不能像上面写的那样做,但是有什么办法吗?

【问题讨论】:

    标签: c# generics .net-3.5


    【解决方案1】:

    你不能,但你也不必。

    public void DoSmth<T>(T obj)
        where T : Superclass
    {
    
       //untested but something like this
        Subclass obj2 = (obj as Subclass);   
        if(obj2 != null)
        {
            DoSmth2(obj2);
        }
        //...
    }
    

    【讨论】:

    • 你必须先像这样转换为“object”:Subclass obj2 = (Subclass) (object) obj;
    • 我认为我的最后一次编辑符合这一点。
    猜你喜欢
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多