private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "|*.csv";
DialogResult result = openFileDialog.ShowDialog();
// if user clicks on ok button that path
// will be copied path textbox
if (result == DialogResult.OK)
{
String name = openFileDialog.FileName;
UpperTextbox.Text = File.ReadAllText(name);
}
}
如何制作变量" name"全局,以便每个方法都使用该变量
答案 0 :(得分:1)
请尝试以下方法,在类的范围内声明Filename而不是函数范围。有关变量范围http://www.codecandle.com/articles/csharp/variables/variable-scope.html
的其他说明,请查看以下链接string Filename {get; set;}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "|*.csv";
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)//if user clicks on ok button that path will be copied path textbox
{
Filename = openFileDialog.FileName;
UpperTextbox.Text = File.ReadAllText(name);
}
答案 1 :(得分:0)
我不确定你的意图或实际意思,但我相信是这样的:
public class Example
{
private string id;
public Example(string id)
{
this.id = id;
}
public void Test()
{
// Holds initial value from Constructor.
Console.WriteLine(id);
// Modified to new value.
id = "7";
Console.WriteLine("7");
}
}
因此,本质上发生的是id
传递的初始值,在object
的持续时间内将包含该值。除非对象中的另一个方法修改了值,否则内存将反映新值。
您实际上也可以使用 Property 执行相同的操作。
public class Container
{
public string Id {get; set; }
}
public class Example
{
private Container container;
public Example(Container container)
{
this.container = container;
}
public void Tester()
{
// Same Value when object created.
Console.WriteLine(container.Id);
// Modified Value:
container.Id = "New Value";
}
}
假设您可以更改该值,但您可以通过其他方式执行此操作。如果您的值从不更改。您可能只想使用const
。
private const string id = "Universal Value";
对象的生命周期id
将始终代表Universal Value
。希望这有所帮助,一些澄清会有所帮助。