public string的值始终为null

时间:2014-06-27 12:27:38

标签: c# string winforms public

我几天前开始学习C#并且我遇到了公共字符串的问题,我目前正在尝试编写一个复制和替换文件以供练习的程序但是我有一个公共字符串的问题,无论我多少尝试更改代码,我都无法自己弄清楚,所以我来到这里寻求帮助

我做错了什么?

以下是代码:

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";

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; } } }

3 个答案:

答案 0 :(得分:5)

if (fbd.ShowDialog() == DialogResult.OK)
{
        string sSelectedPath = fbd.SelectedPath;
}

您使用string关键字在此处声明 new 变量。它没有设置属性。只需删除string即可。 E.g。

if (fbd.ShowDialog() == DialogResult.OK)
{
        sSelectedPath = fbd.SelectedPath;
}

答案 1 :(得分:3)

你的错误在这里:

if (choofdlog.ShowDialog() == DialogResult.OK)
{
    string sSelectedPath = choofdlog.FileName;
}

您使用的是局部变量,而不是成员变量。所以,写:

if (choofdlog.ShowDialog() == DialogResult.OK)
{
    sSelectedPath = choofdlog.FileName;
}

或者,更好的是,如果您不想犯错,请在编写成员变量或方法时使用this.

if (choofdlog.ShowDialog() == DialogResult.OK)
{
    this.sSelectedPath  = choofdlog.FileName;
}

答案 2 :(得分:1)

替换

 string s = choofdlog.FileName;

  s = choofdlog.FileName;