实例化一个对象时出现奇怪的错误
问题描述:
下面是我的代码在我的项目中的文件,你可以看到我在Page_Load中实例化一个叫做“SecretNumber”的类的对象。我最近在访问按钮函数中的对象引用时遇到了问题,因为我忘记将该引用从范围中删除(private SecretNumber guessNr)。实例化一个对象时出现奇怪的错误
但是,由于某种奇怪的原因,此代码会生成以下错误:“字段'_Default.guessNr'永远不会分配给,并且将始终将其默认值为空。
如果我删除“private SecretNumber guessNr”(正在生成错误),则无法从按钮功能到达对象引用的问题再次出现,因此显而易见的是为对象分配引用。
我怎么得到这个错误以及如何解决它?
public partial class _Default : System.Web.UI.Page
{
private SecretNumber guessNr;
protected void Page_Load(object sender, EventArgs e) {
SecretNumber guessNr = new SecretNumber();
}
protected void btnCheckNr_Click(object sender, EventArgs e) {
if (!Page.IsValid){
return;
}
// The rest of the code goes here
}
}
答
你需要让你的Page_Load方法
private SecretNumber guessNr; // declared field here
protected void Page_Load(object sender, EventArgs e) {
guessNr = new SecretNumber();
}
内微妙的变化,你有它的样子,你在声明同名的局部变量。它在方法内部隐藏了类级字段。
int x; // this is a class level field
int y; // same
public void Foo()
{
int x; // this is a local of the same name
this.x = 7; // this is how you would access the class field from this method
y = 4; // no need for "this." for disambiguation
}
你甚至不能复制/粘贴答案? http://*.com/a/9244437/932418 – 2012-02-11 23:35:47
可能重复的[无法访问实例化对象c#/ asp.net](http://*.com/questions/9244405/cant-access-instantiated-object -c-asp-net) – 2012-02-11 23:36:22
它不是重复的。这里的区别在于我添加了“private SecretNumber guessNr”,这是一条重要的路线。顺便说一句,这个问题是不同的。 – holyredbeard 2012-02-11 23:57:04