【问题标题】:How to solve generics error CS0311?如何解决泛型错误 CS0311?
【发布时间】:2017-05-25 01:46:03
【问题描述】:

我搜索了网络和 stackoverflow,发现了许多处理 CS0311 错误的帖子。没有一个场景与我的相似。我有一个从泛型类继承的泛型类。

请注意BusinessBaseCSLA 框架中的一个类

我错过了什么?

public interface Itest
{
    int Digit();
}

class BB : Itest
{
    public int Digit()
    {
        return 20;
    }
}


class Test<T> : BusinessBase<T>, Itest where T : Test<T>, Itest
{
    public int Digit()
    {
        return 30;
    }
}

Test<Itest> test = new Test<Itest>(); //error CS0311

错误 CS0311 类型 'MyTestApp.Itest' 不能用作泛型类型或方法 'A&lt;T&gt;' 中的类型参数 'T'。没有从'MyTestApp.Itest''MyTestApp.A&lt;MyTestApp.Itest&gt;' 的隐式引用转换。我的测试应用程序

【问题讨论】:

标签: c# generics inheritance interface csla


【解决方案1】:

我同意编译器。 T 在您的场景中是 Itest。你的where 条件要求T : Test&lt;T&gt;(这听起来很可疑),这需要ITest : Test&lt;ITest&gt; ...但ITest 显然不需要(并且不能): Test&lt;ITest&gt;

目前还不清楚你打算做什么,但我怀疑你的意思是:

class Test<T> where T : Itest

和:

Test<BB> test = new Test<BB>();

【讨论】:

  • 我已经编辑了我的代码。我从 CSLA 对象继承。如果我没有在约束中包含 Test 我会得到一个类定义错误。
【解决方案2】:

你可以这样做:

interface Itest {}

class BusinessBase<T> {

}

class Test<T> : BusinessBase<T>, Itest where T : Test<T>, Itest {
    public int Digit() {
        return 30;
    }
}

class IT : Test<IT>, Itest {

}

class Program {
    public static int Main() {

        var t = new Test<IT>();
        t.Digit();
        return 0;
    }
}

对我来说,泛型的使用真的很糟糕,但这就是 CSLA 的工作原理......

【讨论】:

  • 谢谢。我会给你投票,但是我是新用户并且没有足够的权限。一旦我获得它就会这样做:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多