2013-09-06 11 views
13

Ho scritto codice in WPF. In primo luogo, ho scritto un progetto separato per testare il lavoro con un dispositivo COM port e ha funzionato bene. Successivamente ho deciso di integrarlo in un altro progetto, ma ottengo un errore. Non ho cambiato il codice; Sono appena stato copiato in un nuovo file di codice.Errore in C#: "È richiesto un riferimento a un oggetto per campo, metodo o proprietà non statici"

Questo codice funziona bene:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 
using System.IO.Ports; 
using System.Windows.Threading; 

namespace WpfApplication2 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      serial.BaudRate = 9600; 
      serial.Handshake = System.IO.Ports.Handshake.None; 
      serial.Parity = Parity.None; 
      serial.DataBits = 8; 
      serial.StopBits = StopBits.One; 
      serial.ReadTimeout = 200; 
      serial.WriteTimeout = 500; 
      serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recieve); 
     } 

     SerialPort serial = new SerialPort(); 
     private string recieved_data; 

     private delegate void UpdateUiTextDelegate(string text); 

     private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 
     { 
      if (serial.IsOpen) 
      { 
       try 
       { 
        recieved_data = serial.ReadLine(); 
        Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(DisplayText), recieved_data); 
       } 
       catch (Exception ex) 
       { 
        MessageBox.Show(ex.ToString()); 
       } 
      } 
     } 

     private void DisplayText(string code) 
     { 
      textBox1.AppendText(string1); 
     } 

     private void button1_Click(object sender, RoutedEventArgs e) 
     { 
      ListBoxItem lbi = new ListBoxItem(); 
      lbi = (ListBoxItem)listBox1.SelectedItem; 
      serial.Close(); 
      serial.PortName = "COM" + (string)lbi.Content; 
      try 
      { 
       serial.Open(); 
       textBox1.AppendText("Device opened at " + serial.PortName + '\n'); 
      } 
      catch (Exception ex) 
      { 
       textBox1.AppendText(ex.Message + '\n'); 
      } 
     } 
    } 
} 

Ma questo non vuole lavorare, e non riesco a capire il motivo per cui:

using System.IO.Ports; 
using System.Windows.Threading; 
using System; 
using System.Windows; 

namespace PresidentProtocol 
{ 
    public class QRBarCode 
    { 
     // private SerialPort serial = new SerialPort(); 

     public QRBarCode(string com) 
     { 
      serial.BaudRate = 9600; 
      serial.Handshake = System.IO.Ports.Handshake.None; 
      serial.Parity = Parity.None; 
      serial.DataBits = 8; 
      serial.StopBits = StopBits.One; 
      serial.ReadTimeout = 200; 
      serial.WriteTimeout = 500; 
      serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recieve); 
      serial.Close(); 
      serial.PortName = com; 
      try 
      { 
       serial.Open(); 
      } 
      catch (Exception) 
      { 
       MessageBox.Show("Error opening COM port."); 
      } 
     } 

     SerialPort serial = new SerialPort(); 
     private string recieved_data; 


     private delegate void UpdateUiTextDelegate(string text); 

     private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 
     { 
      if (serial.IsOpen) 
      { 
       try 
       { 
        recieved_data = serial.ReadLine(); 
        Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(DisplayText), recieved_data); 
       } 
       catch (Exception ex) 
       { 
        MessageBox.Show(ex.ToString()); 
       } 
      } 
     } 

     private void DisplayText(string code) 
     { 
      MessageBox.Show(code); 
     } 
    } 
} 

Errore:

An object reference is required for the non-static field, method, or property 'System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority, System.Delegate, object)' E:\C#\PresidentProtocol\PresidentProtocol\classes\QRCodeReader.cs

su questa riga di codice:

Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(DisplayText), recieved_data); 
+0

possibile duplicato del [problemi Dispatcher.BeginInvoke] (http://stackoverflow.com/questions/2596801/dispatcher-begininvoke-problems) – Heslacher

risposta

32

Nel primo codice, ci si trova in una classe che eredita da Window, quindi si dispone di una proprietà Dispatcher nell'ambito, che restituisce un'istanza di Dispatcher. Nel secondo codice, sei nella classe QRBarCode, che non ha una proprietà Dispatcher; quindi il compilatore presume che tu stia facendo riferimento al tipo Dispatcher e prova a chiamare Invoke su questo tipo, ma poiché non è un metodo statico, non può essere chiamato direttamente sul tipo.

È necessaria un'istanza di Dispatcher per chiamare Invoke; è possibile utilizzare l'uno dal l'applicazione:

Application.Current.Dispatcher.Invoke(...); 
Problemi correlati