加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 泛型和接口问题

发布时间:2020-12-15 19:46:29 所属栏目:百科 来源:网络整理
导读:给出以下类和接口: public class TestT{}public interface ITestingT{ TestT LoadTest();} 我可以添加一个具有以下内容的类: public class TestManager : ITestingobject{ #region ITesting public Testobject LoadTest() { return new Testobject(); } #e
给出以下类和接口:

public class Test<T>
{
}

public interface ITesting<T>
{
    Test<T> LoadTest();
}

我可以添加一个具有以下内容的类:

public class TestManager : ITesting<object>
{
    #region ITesting

    public Test<object> LoadTest()
    {
        return new Test<object>();
    }

    #endregion
}

哪个工作正常,并没有错误.如果我尝试用以下内容替换该类:

public class TestDerived : Test<object>
{
}

public class TestDerivedManager : ITesting<object>
{
    #region ITesting

    public TestDerived LoadTest()
    {
        return new TestDerived();
    }

    #endregion
}

我现在收到以下错误:

Error   'TestDerivedManager' does not implement interface member 'ITesting.LoadTest()'. 'TestDerivedManager.LoadTest()' cannot implement 'ITesting.LoadTest()' because it does not have the matching return type of 'Test'.

但对我来说,似乎这应该起作用,因为TestDerived是Test< object>.我显然在这里没有正确理解.有人可能会指出我为何不正确的细节吗?也许我可能会做些什么来纠正它?

解决方法

您想要的功能称为返回类型协方差.它是c的一个特性,但不是c#的特征,所以你必须做错误所说的.

我建议你做一个调用你的公共方法的显式接口实现.这样你就可以获得两全其美.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读