在其成员函数c#中进一步约束泛型类

时间:2015-07-21 13:10:24

标签: c# oop generics

这里没有经验丰富的仿制药。如果方法的类型超出其类型约束,我是否能够限制它的类型约束?

这是我尝试过的(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不相同,因此无法编译。我可以使用一些魔法演员吗?

1 个答案:

答案 0 :(得分:2)

只需将返回类型更改为List<SafeOffer<TBot>>

public static List<SafeOffer<TBot>> 
    DivideOffer<TBot>(IEnumerable<BotAccountDetailsBase> accounts, List<ItemData> items) 
        where TBot : BotAccountDetailsBase