调用接口方法我想调用一个接口方法使用实现该接口的类的引用。我正在使用反射,但我的代码不工作,我得到空对象引用异常。代码如下:使用参考类
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。这是一个面试问题,用反思来称呼它。 –
使用反射是在专家级别的东西,你只有当你真的需要它时使用它。这非常罕见。如果你是优秀的程序员,你永远不需要反思;) –