【问题标题】:Call interface method using reference of class使用类的引用调用接口方法
【发布时间】:2016-12-01 06:58:30
【问题描述】:

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

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

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

【问题讨论】:

  • 只需将您的类转换为接口并调用您的方法。你不需要反思
  • 感谢 M. kazem Akhgary。这是一个用反射来称呼它的面试问题。
  • 使用反射是专家级的东西,只有在真正需要时才使用它。这是非常罕见的。如果你是优秀的程序员,你永远不需要反思;)

标签: c# .net interface


【解决方案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);

【讨论】:

  • 谢谢!有效。但现在我想调用 IntB.MethodFirst。我怎么称呼它?
【解决方案2】:
        IntA classA = new ClassA();
        classA.MethodFirst();
        Console.ReadLine();

【讨论】:

    猜你喜欢
    • 2015-07-09
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2023-04-03
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多