【发布时间】: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。这是一个用反射来称呼它的面试问题。
-
使用反射是专家级的东西,只有在真正需要时才使用它。这是非常罕见的。如果你是优秀的程序员,你永远不需要反思;)