gpt4 book ai didi

c# - 如何在c#中实现泛型多态?

转载 作者:太空狗 更新时间:2023-10-29 22:33:40 27 4
gpt4 key购买 nike

为了避免混淆我总结了一些代码:

namespace ConsoleApplication1
{
class Program
{
static void Main()
{
IManager<ISpecificEntity> specificManager = new SpecificEntityManager();
IManager<IIdentifier> manager = (IManager<IIdentifier>) specificManager;
manager.DoStuffWith(new SpecificEntity());
}
}

internal interface IIdentifier
{
}

internal interface ISpecificEntity : IIdentifier
{
}

internal class SpecificEntity : ISpecificEntity
{
}

internal interface IManager<TIdentifier> where TIdentifier : IIdentifier
{
void DoStuffWith(TIdentifier entity);
}

internal class SpecificEntityManager : IManager<ISpecificEntity>
{
public void DoStuffWith(ISpecificEntity specificEntity)
{
}
}
}

当我调试代码时,我在 Main() 中得到一个 InvalidCastException .

我知道 ISpecificEntity工具 IIdentifier .但显然是来自 IManager<ISpecificEntity> 的直接转换进入 IManager<IIdentifier>不起作用。

我认为使用协方差可以解决问题,但更改 IManager<TIdentifier>进入IManager<in TIdentifier>也无济于事。

那么,有没有办法投 specificManager进入 IManager<IIdentifier>

谢谢,祝一切顺利。

最佳答案

IManager<IIdentifier>你可以这样做:

IIdentifier entity = new NotSpecificEntity();
manager.DoStuffWith(entity);

这将导致异常,在您的 SpecificEntityManager 中, 因为它只接受 ISpecificEntity 类型的参数

更新:您可以在 Eric Lippert's blog 阅读有关 C# 中协变和逆变的更多信息

关于c# - 如何在c#中实现泛型多态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10211072/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com