问题描述
- C#一个小程序出现NullReferenceException
-
刚刚接触反射技术,但并不理解,对着资料打的程序
namespace 反射
{
class Program
{class User { private int _id; //模拟一个数据库中User的实体 public int ID { get { return _id; } set { _id = value; } } private string _name; public string Name { get { return _name; } set { _name = value; } } }
interface IUser
{
void Insert(User user); //一个从数据库中获取User的接口
User GetUser(int id);} class SqlserverUser : IUser //继承IUser的sql类 { public void Insert(User user) { Console.WriteLine("在sql中插入数据"); //模拟的方法 } public User GetUser(int id) { Console.WriteLine("在sql中得到一条记录"); return null; } } class AccessUser : IUser { public void Insert(User user) { Console.WriteLine("在Access中插入数据"); } public User GetUser(int id) { Console.WriteLine("在Access中得到一条记录,{0}",id); return null; } } class Department { private int _id; public int ID //数据库中的department实体 { get { return _id; } set { _id = value; } } private string _location; public string Location { get { return _location; } set { _location = value; } } } interface IDepartment { void Insert(Department department); //获取Department的接口 Department GetDepartment(int id); } class SqlserverDepartment : IDepartment { public void Insert(Department department) //和上面的差不多 { Console.WriteLine("在sql中插入数据"); } public Department GetDepartment(int id) { Console.WriteLine("在sql中得到一条记录"); return null; } } class AccessDepartment : IDepartment { public void Insert(Department department) { Console.WriteLine("在Access中插入数据"); } public Department GetDepartment(int id) { Console.WriteLine("在Access中得到一条记录"); return null; } } class DataAccess //这个类完全是照抄资料上的,并不是很理解 { private static readonly string AssemblyName = "反射"; private static readonly string db = "Sqlserver"; public static IUser CreateUser() { string className = AssemblyName + "." + db + "User"; return (IUser)Assembly.Load(AssemblyName).CreateInstance(className); } public static IDepartment CreateDepartment() { string className = AssemblyName + "." + db + "Department"; return (IDepartment)Assembly.Load(AssemblyName).CreateInstance(className); } } static void Main(string[] args) { User user = new User(); IUser iu = DataAccess.CreateUser(); iu.Insert(user); } }
}
执行时会抛出NullReferenceException:未将对象引用设置到对象的实例 上面显示的是最后一行代码有问题
?求教各位大神是哪儿出错了 using System.Reflection;在程序里有添加
解决方案
既然是iu.Insert(user)出了问题,那就应该在Insert的实现方法里面设断点跟踪才是,空指针异常的情况一般发生在 对象实例为空却还调用这个实例的属性或方法 的时候,那就设断点看看iu是不是为空呗,如果不为空就跟踪到Insert方法里面呗,总有一个对象实例是空的却要对他进行操作才会有这个异常的。。。。。。再说下去就太小看你了
时间: 2025-01-27 05:06:19