gpt4 book ai didi

c# - 分层嵌套通用接口(interface)

转载 作者:行者123 更新时间:2023-11-30 16:56:47 24 4
gpt4 key购买 nike

我有一个层次嵌套的通用接口(interface)链,为了举例,它看起来像这样:

ICar<TWheels, TBolts>
where TWheels : IWheels<TBolts>
where TBolts : IBolts
{
IEnumerable<TWheels> Wheels { get; set; }
}

IWheels<TBolts>
where TBolts : IBolts
{
IEnumerable<TBolts> Wheels { get; set; }
}

IBolts
{

}

这是处理这些通用接口(interface)的明智方式吗?

它使定义方法看起来像这样:

public TCar GetCar<TWheels, TBolts>(int id)
where TCar : ICar<TWheels, TBolts>
where TWheels : IWheels<TBolts>
where TBolts : IBolts
{
...
}

有什么办法可以减少这个代码签名吗?

最佳答案

应非常小心地使用 C# 中的泛型,以避免出现您遇到过的问题。我建议修改接口(interface)层次结构并丢弃泛型:

interface ICar
{
IEnumerable<IWheel> Wheels { get; set; }
}

interface IWheel
{
IEnumerable<IBolt> Bolts { get; set; }
}

interface IBolt
{
}

然后看看这些接口(interface)参与的用例会很棒。
可能会有非常罕见的情况,当您需要 IR16Wheel 而不是 IWheel 时,类型转换就足够了。
可能,将非通用接口(interface)与通用接口(interface)配对就足够了:

interface IWheel<TBolt> : IWheel
where TBolt : IBolt
{
IEnumerable<TBolt> Bolts { get; set; }
}

并使用像这样的非泛型方法:

public ICar GetCar(int id) { }

但也在更具体的情况下使用泛型。

关于c# - 分层嵌套通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27502463/

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