Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从非泛型类的泛型方法派生泛型方法_C#_.net_Generics - Fatal编程技术网

C# 从非泛型类的泛型方法派生泛型方法

C# 从非泛型类的泛型方法派生泛型方法,c#,.net,generics,C#,.net,Generics,我有一个带有泛型方法的非泛型基类,我想通过添加一些额外的代码来扩展这个方法,而方法的其余部分应该通过调用base.method保持不变 这里有一个例子 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 refere

我有一个带有泛型方法的非泛型基类,我想通过添加一些额外的代码来扩展这个方法,而方法的其余部分应该通过调用base.method保持不变

这里有一个例子

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**
}
公共覆盖列表MyMethod()
{
//在这里做些工作
...
// 
return base.MyMethod();//**我在这里得到一个错误,指出T必须是引用类型**
}

基本方法上似乎有类约束。您只需要在覆盖上具有相同的约束

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

我试过这个,它编译得很好:

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>();
    }
}
公共类基
{
//基方法具有“类”约束
公共虚拟列表MyMethod(),其中T:class
{
返回新列表();
}
}
派生的公共类:基
{
//重写不会声明任何约束;约束是继承的
公共重写列表MyMethod()
{
//基本呼叫工作正常
返回base.MyMethod();
}
}

您的错误不在您发布的代码中。它必须在其他地方。

您可能希望将语言指定为标记;看起来像C#,但我不是肯定的。@pointy我添加了C#标记,因为
override
关键字在那里…它是C#.net抱歉,你们太快了。既然你们正在重写基类,你们怎么能确定
base.MyMethod
将返回一个
列表呢?因为base.MyMethod的签名是这样说的。List MyMethod()是的,有一个约束,但我不能添加我自己的约束,因为约束是继承的。@Ivan,你需要在覆盖上指定相同的约束,约束不是隐式继承的。编译器抱怨覆盖的约束是从基方法继承的。@Ivan你说得对,我做了一个dotnetpad粘贴,我不知道你做错了什么。您可能想发布您的基类,我标记为正确,因为如果在基类的方法中没有指定约束,那么这种方法就是在派生方法中引入它们的正确方法。谢谢大家的帮助!非常感谢!编辑:标签消失了,我想我只能将一个答案标记为正确。很抱歉另一个更正确:)感谢Timwi,我的坏(Java根)虚拟没有在基类方法上指定。现在我必须找出如何克服这个限制:(@Ivan:要么使基类方法虚拟,要么(如果你不能)给你的方法一个不同的名称(但相同的泛型类型约束)。