【问题标题】:No Extension Method for Client Name in C#C# 中没有客户端名称的扩展方法
【发布时间】:2015-12-19 17:14:22
【问题描述】:

给定以下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NetworksApi.TCP.CLIENT;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Form1 client;
        public Form1()
        {
            InitializeComponent();
        }


        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
             if (textBox3.Text!= "" &&textBox4.Text!="")
             {
                 client = new Form1();
                 client.ClientName = textBox4.Text;
                 client.ServerIp = textBox3.Text;
                 client.Connect();
             }
             else
             {
                 MessageBox.Show("Fill it completely");
             }
        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(System.Environment.ExitCode);
        }
    }
}

每当我尝试编译时都会收到以下错误消息:

“WindowsFormsApplication1.Form1”不包含定义 ClientName 并且没有扩展方法“ClientName”接受第一个 类型参数。

你知道如何解决这个问题吗?

【问题讨论】:

    标签: c# asp.net webforms


    【解决方案1】:

    Windows 窗体类上没有 ClientName 属性。但是,由于您是从 Form 继承的,因此您可以添加一个。但这也没有意义。您确定希望Form1 类型的变量具有ClientNameServerIP 的属性和Connect() 的方法吗?您更有可能想要一些其他预先存在的课程或制作自己的课程。

    public class ClientService
    {
        public string ClientName {get; set;}
        public string ServerIp {get; set;}
    
        public void Connect()
        {
            //logic here
        }
    }
    

    并将您的 UI 逻辑更改为

    if (!String.IsNullOrEmpty(textBox3.Text) && !String.IsNullOrEmpty(textBox4.Text))
    {
        var client = new ClientService();
        client.ClientName = textBox4.Text;
        client.ServerIp = textBox3.Text;
        client.Connect();
    }
    else
    {
        MessageBox.Show("Fill it completely");
    }
    

    【讨论】:

      【解决方案2】:

      这是 .NET 中 Form 类的文档:https://msdn.microsoft.com/en-us/library/system.windows.forms.form(v=vs.110).aspx

      请注意,没有列出 ClientName 的成员。你不能引用它,因为它不存在。

      【讨论】:

        猜你喜欢
        • 2019-04-28
        • 2021-11-15
        • 2018-08-24
        • 1970-01-01
        • 1970-01-01
        • 2019-07-16
        • 2021-08-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多