gpt4 book ai didi

c# - 命名空间导致 NullReferenceException?

转载 作者:行者123 更新时间:2023-12-04 16:58:59 29 4
gpt4 key购买 nike

我有以下程序,这是一段示例代码,展示了 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。为什么会这样?

最佳答案

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

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

关于c# - 命名空间导致 NullReferenceException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22736736/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com