C#“对象引用未设置为对象的实例"获取类型/获取属性 [英] C# "Object reference not set to an instance of an object" Get Type / Get Property

查看:159
本文介绍了C#“对象引用未设置为对象的实例"获取类型/获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我收到一个错误:对象引用未设置为对象的实例".我不太清楚为什么……这是代码:

Hi guys I'm receiving an error: "Object reference not set to an instance of an object". I'm not quite sure why... Here's the code:

public void LoadUserContacts(ListBox FriendsLb)
{
   FriendsLb.DisplayMember = "Display";
   var query = from o in Globals.DB.Friends
               where o.UserEmail == Properties.Settings.Default.Email
               select new
               {
                   FirstName = o.FirstName,
                   LastName = o.LastName,
                   Email = o.Email,
                   Display = string.Format("{0} {1} - ({2})", o.FirstName, o.LastName, o.Email),
                };
   FriendsLb.DrawMode = DrawMode.OwnerDrawVariable;

   foreach (object contact in query.ToList())
   {
       string details = query.GetType().GetProperty("Display").ToString();
       FriendsLb.Items.Add(new Contacts(Properties.Resources.avatar, details));
       FriendsLb.DrawItem += FriendsLb_DrawItem;
       FriendsLb.MeasureItem += FriendsLb_MeasureItem;
    }
}

哪个代码导致了错误:

string details = query.GetType().GetProperty("Display").ToString();

有什么想法吗?我正在尝试从查询中获取显示属性:

Any ideas? I'm trying to get the display property from the query:

Display = string.Format("{0} {1} - ({2})", o.FirstName, o.LastName, o.Email),

推荐答案

您尝试获取查询的类型,然后获取该类型的"Display"属性,而不是数据库中列的返回值

You are trying to get the type of the query, and then the property of "Display" of the type, not the return value of the column in the database

查询的类型将不具有属性"display".您需要做更多类似的事情:

The type of the query will not have that the property "display". You need to do something more like:

string property = contact.GetProperty("Display", typeof(string));

string details = property.Name;

我希望它能使您走上正确的轨道.

I hope it puts you on the right track.

此外,在该行设置一个断点,以查看该行的哪一部分是空引用,以便轻松查明问题出在哪里.

Also, set a breakpoint at that row to see what part of the line is a null reference to easily pinpoint where where problem is.

这篇关于C#“对象引用未设置为对象的实例"获取类型/获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆