簡體   English   中英

錯誤非靜態字段需要對象引用

[英]Error An object reference is required for the non-static field

我試圖將我的代碼作為新線程運行,現在出現錯誤。非靜態字段,方法或第59行foreach(目錄中的字符串dirPath)的非靜態字段,方法或屬性'Deploy.Form1.textBox1'需要對象引用。 GetDirectories(textBox1.Text,“ *”

namespace Deploy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            {
                FolderBrowserDialog objFolderDialog = new FolderBrowserDialog();
                textBox1.Text = GetNetworkFolders(objFolderDialog);

                NewThread();
            }
        }

        public static string GetNetworkFolders(FolderBrowserDialog oFolderBrowserDialog)
        {
            Type type = oFolderBrowserDialog.GetType();
            System.Reflection.FieldInfo fieldInfo = type.GetField("rootFolder", BindingFlags.NonPublic | BindingFlags.Instance);
            fieldInfo.SetValue(oFolderBrowserDialog, (Environment.SpecialFolder)18);
            if (oFolderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                return oFolderBrowserDialog.SelectedPath;
            }
            else
            {
                return "";
            }

        }
            static void Main( string[] args )
            {
             Thread t = new Thread( NewThread );
             t.Start();
            }

            static void NewThread()
            {
                foreach (string dirPath in Directory.GetDirectories(textBox1.Text, "*",
                SearchOption.AllDirectories))
                Directory.CreateDirectory(dirPath.Replace(textBox1.Text, textBox2.Text));

                foreach (string newPath in Directory.GetFiles(textBox1.Text, "*.*",
                SearchOption.AllDirectories))
                File.Copy(newPath, newPath.Replace(textBox1.Text, textBox2.Text), true);

        }
    }
}

由於DeanOC聲明的確切原因,您需要在試圖在新線程中訪問的文本框控件上使用Invoke方法。 請嘗試以下操作:

    string  directory = string.Empty;
    textBox1.Invoke((MethodInvoker)delegate {
       directory = textBox1.Text; // runs on UI thread
    });

    string  directory2 = string.Empty;
    textBox2.Invoke((MethodInvoker)delegate {
       directory = textBox2.Text; // runs on UI thread
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM