gpt4 book ai didi

C# 无法访问外部类型的非静态成员

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:58 25 4
gpt4 key购买 nike

你好,我是一名初级程序员,所以如果这个问题已经得到回答或没有意义,请原谅 n=me。我的问题是我使用的是 C#,但我无法从我创建的文件之一访问标签。但是,在我重新启动计算机之前,该文件一直有效。这是代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Resources;

namespace Moneypoly
{
public partial class mainForm
{

public class chance
{
public void chanceOptionOne()
{
discriptionPlayer1.Text = "";
}
}

}
}

discriptionPlayer1.Text 在这里给出错误,错误 141 无法通过嵌套类型“Moneypoly.mainForm.chance”访问外部类型“Moneypoly.mainForm”的非静态成员

考虑到它在我的其他文件中有效并且代码相同,它应该有效。其中一个文件代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;

namespace Moneypoly
{
public partial class mainForm : Form
{
public mainForm()
{
InitializeComponent();
giantView1.SizeMode = PictureBoxSizeMode.StretchImage;
giantView2.SizeMode = PictureBoxSizeMode.StretchImage;
giantView1.Image = Properties.Resources.startPlayerNoOne;
giantView2.Image = Properties.Resources.startPlayerNoOne;
player2Roll.Visible = false;
dicePlayer1.Visible = false;
dicePlayer2.Visible = false;
player1Wallet.Text = " $ " + variables.player1Wallet.ToString();
player2Wallet.Text = " $ " + variables.player2Wallet.ToString();
}


private void buttonRollDice_Click(object sender, EventArgs e)
{
movePlayer1();
movePlayer2();
}

private void mainForm_Load(object sender, EventArgs e)
{

}

private void player1_Click(object sender, EventArgs e)
{

}

private void player1Roll_Click(object sender, EventArgs e)
{
movePlayer1();
player1Roll.Visible = false;
player2Roll.Visible = true;
dicePlayer1.Visible = true;
}

private void player2Roll_Click(object sender, EventArgs e)
{
movePlayer2();
player2Roll.Visible = false;
player1Roll.Visible = true;
dicePlayer2.Visible = true;
}

private void discriptionPlayer1_Click(object sender, EventArgs e)
{

}

private void discriptionPlayer2_Click(object sender, EventArgs e)
{

}
}

}

最佳答案

C# 中的内部类与 Java 中的内部类工作方式不同。

Java 中,内部类可以访问其外部类:在构造期间,每个实例都会存储对其构造该实例的父类的引用。

C# 中,内部类是定义可以访问实例私有(private)成员的类的一种简单方法。换句话说,当您接收存储mainForm 的引用时,您可以读取/写入/修改私有(private)字段并调用私有(private)方法。不存在外部关系

因此,您可以在内部类中定义构造函数到外部,然后设置父类的字段:

namespace Moneypoly {

public partial class mainForm {

public class chance {

private readonly mainForm outer;

public chance (mainForm outer) {
this.outer = outer;
}

public void chanceOptionOne() {
outer.discriptionPlayer1.Text = "";
}

}

}
}

请注意,当您构造一个chance 时,您需要提供对mainForm 的引用:可能使用this

这实际上也是 Java 所做的(除了它对程序员是不可见的)。

此外,在 C#(和 Java)中习惯以大写字母开头类名(在 C# 方法的情况下也是如此)。

关于C# 无法访问外部类型的非静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24222296/

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