如何从类的外部改变公共变量的属性 [英] How to change an attribute of a public variable from outside the class

查看:143
本文介绍了如何从类的外部改变公共变量的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉标题,我不认为我可以解释是正确的:

Sorry about the title, I don't think I could explain it right:

这是一个简单的例子类,这是工作确定。 (我也有一个Save()方法)

This is a simplified example class, this is working ok. (I also have a Save() method)

   public class busItem
    {

        public Item vItem;

        public busItem(int pItem_Id)
        {
            DBDataContext db = new DBDataContext();

            Item vItemQuery = (from i in db.Items
                               where i.Id == pItem_Id
                               select i).FirstOrDefault();

            vItem = new Item();

            vItem.Id = vItemQuery.Id;
            vItem.Desc = vItemQuery.Desc;

        }
    }

这是我的code-背后电话:

And this is my code-behind call:

busItem item = new busItem(1);
item.vItem.Desc = "new description";

问题是,当我尝试过了新的描述,我得到一个空引用异常。我该怎么办呢?

the problem is that when I try passing the "new description", i get a "null reference" exception. How can I do that?

推荐答案

首先,是code不看的权利,至少有两个原因。 pItem在查询未声明;你的意思是pItem_Id?此外,随着新的描述行不以分号结束。除非我在看的确切code你有,有一个很好的机会实际问题win't可见。其次,我怀疑的错误实际上不是,当你将新的描述,但是当你分配vItem.Desc = vItemQuery.Desc。我怎么看不到了新的描述行可能是一个问题,但如果查询返回null,因为它找不到请求的对象,你会得到一个错误尝试获得原始/默认的描述时。

First of all, that code doesn't look right for at least 2 reasons. pItem in the query is not declared; did you mean pItem_Id? Also, the line with "new description" doesn't end with a semicolon. Unless I'm looking at the exact code you have, there's a good chance the actual problem win't be visible. Secondly, I suspect the error is not actually when you assign "new description" but when you assign vItem.Desc = vItemQuery.Desc. I don't see how the "new description" line could be a problem, but if the query returned null because it couldn't find the requested object, you'd get an error when trying to get the original/default description.

编辑:您的确定的你不排除一些显著一张code类的构造函数中声明VITEM的本地实例

Are you sure you didn't exclude some significant piece of code like declaring a local instance of vItem within the constructor?

这篇关于如何从类的外部改变公共变量的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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