C#::中的错误;非静态字段、方法或属性需要对象引用;
我用WPF编写代码。首先,我编写了一个单独的项目,用一个设备测试工作,效果很好。接下来,我决定将它集成到另一个项目中,但我遇到了一个错误。我没有改变密码;我刚把它复制到一个新的代码文件中 此代码运行良好:C#::中的错误;非静态字段、方法或属性需要对象引用;,c#,wpf,delegates,dispatcher,C#,Wpf,Delegates,Dispatcher,我用WPF编写代码。首先,我编写了一个单独的项目,用一个设备测试工作,效果很好。接下来,我决定将它集成到另一个项目中,但我遇到了一个错误。我没有改变密码;我刚把它复制到一个新的代码文件中 此代码运行良好: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using Sy
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');
}
}
}
}
错误:
非静态字段、方法或属性“System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority,System.Delegate,object)”需要对象引用
E:\C\C\PresidentProtocol\PresidentProtocol\classes\QRCodeReader.cs
在这一行代码中:
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(DisplayText), recieved_data);
在第一个代码中,您所处的类继承自
窗口
,因此在作用域中有一个Dispatcher
属性,该属性返回Dispatcher
的实例。在第二个代码中,您位于QRBarCode
类中,该类没有Dispatcher
属性;因此,编译器假定您引用的是Dispatcher
类型,并尝试对该类型调用Invoke
,但由于它不是静态方法,因此无法直接对该类型调用它
您需要一个Dispatcher
实例来调用Invoke
;您可以使用应用程序中的一个:
Application.Current.Dispatcher.Invoke(...);
可能重复的
Application.Current.Dispatcher.Invoke(...);