我有以下程序,它是一个代码示例,显示C#反射如何在类上运行。一切正常,没有任何问题。
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);
}
}
我遇到的问题是,当我在命名空间中包装所有代码时,我突然在Type对象上获得NullReferenceException。为什么会这样?
答案 0 :(得分:4)
因为它不再知道客户在哪里。你需要
Type T = Type.GetType("NameSpaceName.Customer");