如何在c#中调用接口特定方法?

时间:2016-02-25 04:41:26

标签: c#

我有一个界面。在界面内我有3种方法。

public interface interfaceMethod
{
   string methodA();
   string methodB();
   string methodC();
}

我想在没有引用所有接口方法的情况下只调用methodA()的一个方法。如何只调用一种方法而不是引用所有方法。

Public class Class1
{
   public string testCallInterfaceMethod()
   {
       interfaceMethod obj = new interfaceMethod();
       obj.callMethodA();
   }   
}

2 个答案:

答案 0 :(得分:4)

为什么要建立一个接口/合约然后不遵守它?听起来像两个接口的完美用例。

public interface interfaceMethod
{
   string methodA();
}

public interface anotherInterface : interfaceMethod
{
   string methodB();
   string methodC();
}

答案 1 :(得分:0)

界面只是一份合同。一个类可以签署该合同,然后实现合同要求的方法。使用您的界面,以下代码将起作用:

public interface InterfaceMethod
{
   string methodA();
   string methodB();
   string methodC();
}

Public class Class1 : InterfaceMethod
{
   //Implementation of InterfaceMethod interface
   public string MethodA() { /* Code */ }

   public string MethodB() { /* Code */ }

   public string MethodC() { /* Code */ }

   /* Class' other code */
}

其他地方......

public string testCallInterfaceMethod()
{
    InterfaceMethod im = new Class1();
    Console.WriteLine(im.MethodA());
    Console.WriteLine(im.MethodB());
    Console.WriteLine(im.MethodC());
    return null;
}