public string's value is always null
几天前我开始学习C,我在公共字符串方面遇到了问题,我目前正在尝试编写一个程序来复制和替换文件以供实践,但我在公共字符串方面遇到了问题,无论我如何尝试更改代码,我都无法自己解决,所以我来这里寻求帮助。
我做错什么了?
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | namespace Extractor { public partial class Form1 : Form { public string s { get; set; } public string sSelectedPath { get; set; } public string beckup { get; set; } public Form1() { InitializeComponent(); } private void direc_Click(object sender, EventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.Description ="Select a folder"; </p> <wyn> if (fbd.ShowDialog() == DialogResult.OK) { string sSelectedPath = fbd.SelectedPath; } } private void choof_Click(object sender, EventArgs e) { OpenFileDialog choofdlog = new OpenFileDialog(); choofdlog.Filter ="All Files (*.*)|*.*"; choofdlog.FilterIndex = 1; choofdlog.Multiselect = true; if (choofdlog.ShowDialog() == DialogResult.OK) { string s = choofdlog.FileName; } } private void button3_Click(object sender, EventArgs e) { ReplaceFile( s, sSelectedPath, beckup); } public static void ReplaceFile(string FileToMoveAndDelete, string FileToReplace, string BackupOfFileToReplace) { File.Replace(FileToMoveAndDelete, FileToReplace, BackupOfFileToReplace, false); } private void button1_Click(object sender, EventArgs e) { FolderBrowserDialog fbb = new FolderBrowserDialog(); fbb.Description ="Select a folder"; if (fbb.ShowDialog() == DialogResult.OK) { string beckup = fbb.SelectedPath; } } } |
1 2 3 4 | if (fbd.ShowDialog() == DialogResult.OK) { string sSelectedPath = fbd.SelectedPath; } |
您在这里使用
1 2 3 4 | if (fbd.ShowDialog() == DialogResult.OK) { sSelectedPath = fbd.SelectedPath; } |
你的错误在这里:
1 2 3 4 | if (choofdlog.ShowDialog() == DialogResult.OK) { string sSelectedPath = choofdlog.FileName; } |
您使用的是局部变量,而不是成员变量。所以,写:
1 2 3 4 | if (choofdlog.ShowDialog() == DialogResult.OK) { sSelectedPath = choofdlog.FileName; } |
或者,更好的方法是,如果您不想出错,在编写成员变量或方法时使用
1 2 3 4 | if (choofdlog.ShowDialog() == DialogResult.OK) { this.sSelectedPath = choofdlog.FileName; } |
替换
1 | string s = choofdlog.FileName; |
具有
1 | s = choofdlog.FileName; |