【问题标题】:Error An object reference is required for the non-static field错误非静态字段需要对象引用
【发布时间】:2014-03-16 21:04:02
【问题描述】:

我正在尝试将我的代码作为新线程运行,现在我收到错误消息,第 59 行 foreach 上的非静态字段、方法或属性“Deploy.Form1.textBox1”需要对象引用(字符串 dirPath在 Directory.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);

        }
    }
}

【问题讨论】:

  • 除非最新版本的 .Net 发生了变化,否则您不能从原始线程以外的线程直接与 UI 组件交互。如果你想在线程之间传输,我认为你必须使用编组。

标签: c# forms


【解决方案1】:

由于 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
    });

【讨论】:

  • @user2489686,您需要将此代码添加到NewT​​hread方法的开头并使用字符串值而不是直接访问文本框的文本属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多