【问题标题】:How to call method from interface, if object implement this interface?如果对象实现了这个接口,如何从接口调用方法?
【发布时间】:2020-06-28 12:18:20
【问题描述】:

我有一个元素集合

 readonly Deposit[] deposits;

这个集合中的一些元素是实现接口

interface IProlongable
{
    public bool CanToProlong();
}

我需要计算接口中方法返回的true结果的数量

public int CountPossibleToProlongDeposit()
    {
        int count = default;
        foreach (var deposit in deposits)
        {
            if (deposit is IProlongable)
            {
                // Here i need to check if deposit.CanToProlog() is true and increment counter.
            }
        }

        return count;
    }

【问题讨论】:

  • 可以通过deposit.CanToProlong();调用方法

标签: c# collections interface


【解决方案1】:
if (deposit is IProlongable p && p.CanToProlog())
{
    count++;
}

当pattern matching(使用is)时,您可以将结果转换为变量(此处为p)。

p 的类型为 IProlongable,因此您可以访问方法 CanToProlog()。

您还可以使用++ 运算符将count 增加1。

【讨论】:

  • 感谢您的回答)您能否推荐一下我需要为这项任务学习的主题?
  • @saYmon 我的回答中有一个指向模式匹配文档的链接。这应该可以解释一切。
猜你喜欢
  • 2013-08-16
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多