这里对泛型缺乏经验。如果方法的类型位于其类型层次结构的更下方,我是否能够对方法的类型进行比其类约束更多的约束?
这是我尝试过的(BotAccountDetailsBase 派生自 AccountDetailsBase):
public class SafeOffer<TAcc> where TAcc : AccountDetailsBase
{
public readonly TAcc account_;
public readonly List<ItemData> items_;
private SafeOffer(TAcc account, List<ItemData> items)
{
account_ = account;
items_ = items;
}
public static List<SafeOffer<TAcc>> DivideOffer<TBot>(IEnumerable<BotAccountDetailsBase> accounts, List<ItemData> items) where TBot : BotAccountDetailsBase
{
var accounts_to_trade = new List<SafeOffer<TBot>>();
// get the bots of the right type, order by slots
var typed_account = accounts.OfType<TBot>().OrderByDescending(x => x.slotsleft_);
foreach (var acc in typed_account)
{
if (items.Count > 0)
{
var bundle = items.Take(acc.slotsleft_);
items.RemoveAll(x => bundle.Contains(x));
var offer = new SafeOffer<TBot>(acc, bundle.ToList());
accounts_to_trade.Add(offer);
}
}
return accounts_to_trade;
}
}
由于 TAcc 和 TBot 不同,因此无法编译。有什么我可以使用的魔法吗?
最佳答案
只需将返回类型更改为 List<SafeOffer<TBot>>
:
public static List<SafeOffer<TBot>>
DivideOffer<TBot>(IEnumerable<BotAccountDetailsBase> accounts, List<ItemData> items)
where TBot : BotAccountDetailsBase
关于c# - 在其成员函数之一中进一步约束泛型类c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31539989/