首页 > 解决方案 > C# 表单类扩展问题

问题描述

我当前的 Form1.cs 太大,所以我试图将它们分成多个较小的文件,以便代码更易于阅读。但是,我的方法可以满足我的需要,但同时也很烦人,因为我的每个扩展都被视为一种形式。因此,如果我双击扩展名,则会弹出一个表单而不是类。所以我必须继续点击然后按F7。请告知解决方法

Form1.cs

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;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            test();
        }
    }
}

Form1_Ext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication2
{
    public partial class Form1 
    {
        public void test()
        {
            Console.WriteLine("hello");
        }
    }
}

Form1.Desginer.cs

namespace WindowsFormsApplication2
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Text = "Form1";
        }

        #endregion
    }
}

在此处输入图像描述

请看红框,任何扩展类都被视为它自己的一种形式,而不是一个类。在 min 它应该指向 Form1.cs 但它不是。

标签: c#winforms

解决方案


我不确定你在问什么。partial但是,如果您想通过使用类上的关键字将表单的代码拆分为多个文件,Form1并使每个文件看起来是解决方案资源管理器树中 Form1 条目的子项,则需要手动编辑WindowsFormsApplication2。 csproj文件。在你这样做之前,确保你备份它(如果不知道你在做什么,很容易破坏你的项目)。

如果您查看该文件,您将看到如下内容:

  <ItemGroup>
    <Compile Include="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Include="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
    <Compile Include="Form1_Ext.cs" />
    <!-- More entries -->
  </ItemGroup>

您要做的是使“Form1_Ext.cs” DependentUpon主表单条目。所以改变:

<Compile Include="Form1_Ext.cs" />

到:

<Compile Include="Form1_Ext.cs">
  <DependentUpon>Form1.cs</DependentUpon>
</Compile>

我想这就是你要问的。


推荐阅读