作为C#和OOP的新手,我在范围和访问方面遇到了一些新手问题,其中之一是:当主窗体加载类Doc的实例时,将创建Doc,构造函数打开一个Word文档并创建文档中所有图像的列表。列表中的第一个图像显示在图片框中,如下所示:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
public class Doc {
public List<Image> images = new List<Image>();
public Doc(string path) {
// Open Word document, create list of images
}
}
private void Form1_Load(object sender, EventArgs e) {
Doc doc = new Doc("C:\lorem_ipsum.doc");
pictureBox1.Image = doc.images[0];
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e) {
pictureBox1.Image = doc.images[numericUpDown1.Value];
}
}
还有一个 numericUpDown 控件,它应该用于显示不同的图像,这就是问题所在。上面示例中的最后一个代码块不起作用,但我希望它能说明我想做什么。
此问题的最佳实践解决方案是什么(以及一个控件应该能够访问其他控件创建的对象)的类似解决方案?我也试图通过为 Doc 类创建一个方法来解决这个问题,但在从那里访问图片框时遇到了问题。
您的问题是您创建了doc
作为局部变量。您需要类范围内的成员变量:
public partial class Form1 : Form {
private Doc _doc; // Add this line
public Form1() {
InitializeComponent();
}
public class Doc {
public List<Image> images = new List<Image>();
public Doc(string path) {
// Open Word document, create list of images
}
}
private void Form1_Load(object sender, EventArgs e) {
_doc = new Doc("C:\lorem_ipsum.doc");
pictureBox1.Image = _doc.images[0];
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e) {
pictureBox1.Image = _doc.images[numericUpDown1.Value];
}
}
关于范围的一些信息
public class MyClass
{
// myMemberVariable is declared inside class, but outside
// a function. Therefore, it can be accessed from anywhere
// inside the class.
int myMemberVariable;
public void MyFunction()
{
// myLocalVariable is declared inside a function. Therefore,
// it can be accessed only inside this function and nowhere
// else.
int myLocalVariable;
for (int x=0;x<10;x++)
{
// anotherLocalVariable is declared inside a for loop. Therefore,
// this variable can only be used inside this for loop and
// no where else.
int anotherLocalVariable;
}
}
}
将大括号视为范围分隔符。您创建的变量只能在左大括号和右大括号内使用,而不能在大括号外使用。唯一的"部分"例外是static
变量。
只需将doc
设为Form1
的私人领域即可。
public partial class Form1 : Form {
private Doc doc;
public Form1() {
InitializeComponent();
}
public class Doc {
public List<Image> images = new List<Image>();
public Doc(string path) {
// Open Word document, create list of images
}
}
private void Form1_Load(object sender, EventArgs e) {
doc = new Doc("C:\lorem_ipsum.doc");
pictureBox1.Image = dok.images[0];
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e) {
pictureBox1.Image = doc.images[numericUpDown1.Value];
}
}
你拥有的doc
有一个局部变量,即它是Form1_Load
的局部变量。这意味着它只存在于该方法中。你想要的是一个成员字段,在Form1
类本身上定义。只要表单存在,它就会一直存在:
public partial class Form1 : Form
{
private Doc m_Doc;
....
private void Form1_Load(object sender, EventArgs e)
{
m_Doc = new Doc("C:\lorem_ipsum.doc");
pictureBox1.Image = m_Doc.images[0];
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
pictureBox1.Image = m_Doc.images[numericUpDown1.Value];
}
}
现在m_Doc
可以访问类中的任何内容(以及嵌套类),但不能访问其他内容,因为它是private
。
我还选择添加m_
后缀。没有必要,人们会整夜争论什么惯例最好,但这就是我更喜欢的!