2016-12-01 67 views
0

调用接口方法我想调用一个接口方法使用实现该接口的类的引用。我正在使用反射,但我的代码不工作,我得到空对象引用异常。代码如下:使用参考类

interface IntA 
{ 
    void MethodFirst(); 
} 

interface IntB 
{ 
    void MethodFirst(); 
} 

class ClassA : IntA, IntB 
{ 
    public void MethodFirst() 
    { 
     Console.WriteLine("this.ClassA.MethodFirst"); 
    } 
    void IntA.MethodFirst() 
    { 
     Console.WriteLine("IntA.ClassA.MethodFirst"); 
    } 
    void IntB.MethodFirst() 
    { 
     Console.WriteLine("IntB.ClassA.MethodFirst"); 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    {    
     Type t = Type.GetType("ClassA"); 
      t.GetMethod("MethodFirst").Invoke(Activator.CreateInstance(t,null), null); 

     Console.ReadLine(); 
    }   
} 

请让我知道我在做什么错在这里。

+3

可简单地把你的类接口并调用你的方法。你不需要反思 –

+0

谢谢M. kazem Akhgary。这是一个面试问题,用反思来称呼它。 –

+1

使用反射是在专家级别的东西,你只有当你真的需要它时使用它。这非常罕见。如果你是优秀的程序员,你永远不需要反思;) –

回答

1

您需要尝试使用该类的完整名称空间创建类的实例。例如,

Type t = Type.GetType("ConsoleApplication1.ClassA"); 

在情况下,如果你想打电话从一个特定接口的方法 -

Type t = Type.GetType("ConsoleApplication1.ClassA"); 
t.GetInterface("ConsoleApplication1.IntB").GetMethod("MethodFirst").Invoke(Activator.CreateInstance(t, null), null); 
+0

谢谢!有效。但是现在我想打电话给IntB.MethodFirst。我怎么称呼它? –

0
 IntA classA = new ClassA(); 
     classA.MethodFirst(); 
     Console.ReadLine();