C# 从类中深层的方法访问变量
如何在foreach循环和下面的try下访问变量名?我需要在我的主课上引用它。对不起,这是个愚蠢的问题C# 从类中深层的方法访问变量,c#,winforms,C#,Winforms,如何在foreach循环和下面的try下访问变量名?我需要在我的主课上引用它。对不起,这是个愚蠢的问题 public class DragDropRichTextBox : RichTextBox { public DragDropRichTextBox() { //Enables drag and drop on this class. this.AllowDrop = true; this.DragDrop += D
public class DragDropRichTextBox : RichTextBox
{
public DragDropRichTextBox()
{
//Enables drag and drop on this class.
this.AllowDrop = true;
this.DragDrop += DragDropRichTextBox_DragDrop;
}
public void DragDropRichTextBox_DragDrop(object sender, DragEventArgs e)
{
string[] _fileText;
_fileText = e.Data.GetData(DataFormats.FileDrop) as string[];
if (_fileText != null)
{
foreach (string name in _fileText)
{
try
{
this.AppendText(BinaryFile.ReadString(name));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
这里是我需要从我的主课中调用它的地方,请参见以下内容:
private void button5_Click(object sender, EventArgs e)
{
{
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
if (DialogResult.OK == pd.ShowDialog(this))
{
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, HERE);
}
}
}
简单明了,你绝对不能
该变量的作用域为该foreach循环。无法在循环之外访问它,因为它甚至不存在于循环之外
如果没有循环,它将被限定在try块的范围内,如果没有循环,它将被限定在方法的范围内。即使在这些情况下,变量也不存在于其范围之外
即使它这样做了,它又有什么价值呢?它是一个迭代变量,因此它在循环的每个过程中都会发生变化。这整件事根本没有意义
如果您需要访问它指向/持有的数据,那么您需要将其存储在类级变量中,或者在本例中,将每个值放入IEnumerable中。这里有一些奇怪的东西,但我只回答您的问题,并将其保留。只是提醒一下,当您在foreach循环中移动时,您所指的名称将不断更改值
public class DragDropRichTextBox : RichTextBox
{
public static List<string> NameList; // Create instance variable
public DragDropRichTextBox()
{
//Enables drag and drop on this class.
this.AllowDrop = true;
this.DragDrop += DragDropRichTextBox_DragDrop;
}
public void DragDropRichTextBox_DragDrop(object sender, DragEventArgs e)
{
string[] _fileText;
_fileText = e.Data.GetData(DataFormats.FileDrop) as string[];
if (_fileText != null)
{
foreach (string name in _fileText)
{
try
{
this.AppendText(BinaryFile.ReadString(name);
NameList.Add(name); // Assign it inside loop
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
private void button5_Click(object sender, EventArgs e)
{
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
if (DialogResult.OK == pd.ShowDialog(this))
{
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, DragDropRichTextBox.Name);
}
}
现在还不清楚你的第一堂课和主课之间的关系。您在一个循环中有一个名称,在这个循环中您可以有多个值,所以您是否要求所有值,第一个值,最后一个值?需要更多的信息。这如何回答他的问题???变量作用域并不是那么奇怪,理解起来也很重要。他问了“名字”,这就给了他。我从未说过范围界定很奇怪,我同意理解这一点很重要,他的问题和编码风格很奇怪。不管怎样,我回答了他提出的问题,同时也提到了他所指的“名称”将随着它在foreach循环中的迭代而改变。你刚才说的是进入了一些奇怪的东西,这让我很困惑。考虑一下你的变化,因为只是浏览代码是不明显的。当我说“奇怪的东西”时,我指的是他的问题,他想达到什么目标,以及他正在采取的方式。我不想深入探讨它应该如何设置,所以我只是回答了他的问题,就我们都看到的一个问题留下了一条评论,然后就放了它。是否可以使用DragDropRichTextBox\u DragDrop.\u fileText然后重新创建foreach循环?我也不知道如何从另一个类访问_fileText变量,因为它基于一个事件,即DragDrop。很抱歉,让我先试试您已经建议的。我感谢你的帮助。谢谢