2014-03-29 39 views
0

我有以下程序,它是一段代码示例,显示了C#反射如何在类上运行。一切正常,没有问题。命名空间导致NullReferenceException?

public class Program 
{ 

public static void Main() 
{ 

    Type T = Type.GetType("Customer"); 
    Console.WriteLine("Information about the Type object: "); 
    Console.WriteLine(T.Name); 
    Console.WriteLine(T.FullName); 
    Console.WriteLine(); 

    Console.WriteLine("Property info:"); 
    PropertyInfo[] myPropertyInfoArray = T.GetProperties(); 

    foreach(PropertyInfo myProperty in myPropertyInfoArray) 
    { 
     Console.WriteLine(myProperty.PropertyType.Name); 
    } 
    Console.WriteLine(); 

    Console.WriteLine("Methods in Customer:"); 
    MethodInfo[] myMethodInfoArray = T.GetMethods(); 

    foreach(MethodInfo myMethod in myMethodInfoArray) 
    { 
     Console.WriteLine(myMethod.Name); 
    } 


    Console.ReadKey(); 
} 

} 


class Customer 
{ 

public int ID {get;set;} 
public string Name {get;set;} 

public Customer() 
{ 
    this.ID = -1; 
    this.Name = string.Empty; 
} 

public Customer(int ID, string Name) 
{ 
    this.ID = ID; 
    this.Name = Name; 
} 

public void PrintID() 
{ 
    Console.WriteLine("ID: {0}", this.ID); 
} 

public void PrintName() 
{ 
    Console.WriteLine("Name: {0}", this.Name); 
} 

} 

是我遇到的问题是,当我包装所有的代码命名空间中,我suddently获得Type对象上一个NullReferenceException。为什么会这样呢?

+0

在哪条线上?什么是您的名字空间名称? –

回答

4

因为它不再知道客户在哪里。您需要

Type T = Type.GetType("NameSpaceName.Customer"); 
+1

如果'Customer'与上面的代码位于相同的命名空间中,这甚至适用。 –

+1

对,因为GetType不知道名称空间 –

+0

非常好,谢谢。 – user3308043