2014-03-29 87 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