使用类的引用调用接口方法

时间:2016-12-01 06:58:30

标签: c# .net interface

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

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();
    }        
}

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

        IntA classA = new ClassA();
        classA.MethodFirst();
        Console.ReadLine();
相关问题