开发者

Derive generic method from generic method of non-generic class

I have a non-generic base cla开发者_运维技巧ss with a generic method I want to extend this method by adding some extra code while the rest of the method should remain the same by calling base.Method

here an example

public override List<T> MyMethod<T>()
{

// do some work in here
...
// 

return base.MyMethod<T>(); // **I get an error here saying that T must be a reference type**
}


Seems like you have a class constraint on your base method. You just need to have the same constraint on the override

public override List<T> MyMethod<T>() where T : class


I tried this and it compiles just fine:

public class Base
{
    // Base method has a 'class' constraint
    public virtual List<T> MyMethod<T>() where T : class
    {
        return new List<T>();
    }
}

public class Derived : Base
{
    // Override does not declare any constraints; constraints are inherited
    public override List<T> MyMethod<T>()
    {
        // base call works just fine
        return base.MyMethod<T>();
    }
}

Your error is not in the code you posted. It must be somewhere else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜