【问题标题】:Error: “an object reference is required for the non-static field, method or property…” [duplicate]错误:“非静态字段、方法或属性需要对象引用……” [重复]
【发布时间】:2017-01-27 19:18:04
【问题描述】:

我有一个用 c# 编写的 WPF 客户端。该程序是一个注册演示程序,您输入一个名称并说出他们是否在这里,然后将其发送到服务器和端口,由用户输入到文本框中。

但是,当尝试在代码中应用它时,我收到错误消息:“非静态字段、方法或属性需要对象引用……”。 这是在“client.connect”行...

namespace client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        public class connectandsend
        {

            //if 'REGISTER' button clicked do this...{
            static void connect()
            {
                TcpClient client = new TcpClient(); // New instance of TcpClient class of the .Net.Sockets
                client.Connect(server_txt.Text, Convert.ToInt32(port_txt.Text)); // Server, Port
                StreamWriter sw = new StreamWriter(client.GetStream()); // New StreamWriter instance
                StreamReader sr = new StreamReader(client.GetStream()); // New StreamReader instance
            }

            /* static void send()
            {
                stream write... name.text and 'here' or 'not here' ticked box?
            }

            }
            */
        }

    }
}

【问题讨论】:

标签: c# wpf object-reference


【解决方案1】:

connect() 方法不能是static,如果您希望能够访问其中的MainWindow 的任何非静态成员。此外,它不能位于另一个类中,除非该类或方法本身也引用了MainWindow 类。

去掉static关键字,把方法移到MainWindow类:

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
    }

    void connect()
    {
        ...
    }
}

或者调用时将server_txt.Text和port_txt.Text传递给方法:

static void connect(string server, int port)
{
    TcpClient client = new TcpClient(); // New instance of TcpClient class of the .Net.Sockets
    client.Connect(server, port); // Server, Port
    StreamWriter sw = new StreamWriter(client.GetStream()); // New StreamWriter instance
    StreamReader sr = new StreamReader(client.GetStream()); // New StreamReader instance
}

主窗口:

connectandsend.connect(server_txt.Text, Convert.ToInt32(port_txt.Text));

【讨论】:

  • 我明白了,我是否正确地说我注释掉的 send() 方法也应该是 void send() 因为它也在尝试访问主窗口的非静态成员?顺便说一句,我选择了第一个选项。
  • 是的,没有静态方法可以访问任何非静态实例成员。如果您的原始问题已解决,请记住接受答案,然后如果您有新问题,请提出新问题。
  • 太好了,很高兴我能了解我的问题并从中吸取教训,答案被接受。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
相关资源
最近更新 更多