2011-02-01 294 views
2

我有一個泛型方法的非泛型基類我想通過添加一些額外的代碼來擴展此方法,而通過調用基類保持該方法的其餘部分保持不變。方法從非泛型類的泛型方法派生泛型方法

這裏的例子

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** 
} 
+0

您可能想要將語言指定爲標記;看起來像C#,但我不積極。 – Pointy 2011-02-01 01:17:32

+0

@pointy由於「override」關鍵字存在,我添加了c#標記... – 2011-02-01 01:18:19

+0

這是C#.net抱歉,你們很快。 – Ivan 2011-02-01 01:19:15

回答

1

我想這同樣的約束,它編譯就好:

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>(); 
    } 
} 

你的錯誤並不在你發佈的代碼。它一定在別的地方。

5

好像你對你的基礎方法的類約束。你只需要對覆蓋