【问题标题】:How to call an interface in C#如何在 C# 中调用接口
【发布时间】:2011-07-14 21:23:43
【问题描述】:
interface ISample
{
    int fncAdd();
}

class ibaseclass
{
    public int intF = 0, intS = 0;
    int Add()
    {
        return intF + intS;
    }
}
class iChild : ibaseclass, ISample
{
    int fncAdd()
    {
        int intTot = 0;
        ibaseclass obj = new ibaseclass();
        intTot = obj.intF;
        return intTot;
    }
}

我想在static void Main(string[] args) 中致电ISample,但我不知道该怎么做。你能告诉我怎么做吗?

【问题讨论】:

标签: c# .net oop interface


【解决方案1】:

接口不能自己实例化。你不能只调用一个接口。您需要实例化一个真正实现接口的类。

接口不会也不能自己做任何事情。

例如:

ISample instance = new iChild(); // iChild implements ISample
instance.fncAdd();

以下问题对此提供了更详细的答案:

【讨论】:

    【解决方案2】:

    您不能“调用”接口或创建它的实例。

    可以做的是让你的类实现接口然后使用它的方法fncAdd

    【讨论】:

      【解决方案3】:

      你的意思是?:

      static void Main(string[] args)
      {
          ISample child = new iChild();
          child.fncAdd();
      }
      

      虽然,正如其他人所说,代码似乎没有正确使用继承。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多