草庐IT

c# - C# : "An object reference is required for the non-static field, method, or property" 错误

coder 2023-07-13 原文

我在 WPF 中编写代码。首先,我编写了一个单独的项目来测试 COM port 的工作。设备,并且运行良好。接下来我决定将它集成到另一个项目中,但我得到了一个错误。我没有更改代码;我只是将它复制到一个新的代码文件中。

此代码运行良好:

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

但是这个不想工作,我不明白为什么:

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

错误:

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

在这行代码中:

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

最佳答案

在第一段代码中,你在一个继承自 Window 的类中,所以你在范围内有一个 Dispatcher 属性,它返回一个 Dispatcher 的实例。在第二个代码中,您在 QRBarCode 类中,它没有 Dispatcher 属性;所以编译器假定您指的是 Dispatcher 类型,并尝试调用此类型的 Invoke,但由于它不是静态方法,因此无法调用直接在类型上。

你需要一个Dispatcher的实例来调用Invoke;您可以使用应用程序中的一个:

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

关于c# - C# : "An object reference is required for the non-static field, method, or property" 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18652767/

有关c# - C# : "An object reference is required for the non-static field, method, or property" 错误的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. Ruby 元类 : why three when defined singleton methods? - 2

    让我们计算MRI范围内的类别:defcount_classesObjectSpace.count_objects[:T_CLASS]endk=count_classes用类方法定义类:classAdefself.foonilendend然后运行:putscount_classes-k#=>3请解释一下,为什么是三个? 最佳答案 查看MRI代码,每次你创建一个Class时,在Ruby中它是Class类型的对象,ruby会自动为这个新类创建“元类”类,这是另一个单例类型的Class对象。C函数调用(class.c)是:rb_define

  6. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  7. ruby-on-rails - Rails 中的 NoMethodError::MailersController#preview undefined method `activation_token=' for nil:NilClass - 2

    似乎无法为此找到有效的答案。我正在阅读Rails教程的第10章第10.1.2节,但似乎无法使邮件程序预览正常工作。我发现处理错误的所有答案都与教程的不同部分相关,我假设我犯的错误正盯着我的脸。我已经完成并将教程中的代码复制/粘贴到相关文件中,但到目前为止,我还看不出我输入的内容与教程中的内容有什么区别。到目前为止,建议是在函数定义中添加或删除参数user,但这并没有解决问题。触发错误的url是http://localhost:3000/rails/mailers/user_mailer/account_activation.http://localhost:3000/rails/mai

  8. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  9. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  10. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

随机推荐