带有 DataGridView 列名称的 CS0108 警告

问题描述

我有一个 DataGridView,其中有一列名为“Location”(与数据库字段相同)。编译时,我收到 CS0108 警告。以下是表单设计器的相关部分:

Form1Designer.cs(271,64,271,72): warning CS0108: 'Form1.Location' hides inherited member 'Form.Location'. Use the new keyword if hiding was intended.

        #region Windows Form Designer generated code
        private void InitializeComponent()
        {
            this.Location = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.SuspendLayout();
            ...
            // 
            // dataGridView1
            // 
            this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.Location,...
            // 
            // Location
            // 
            this.Location.DataPropertyName = "Location";
            this.Location.HeaderText = "Location";
            this.Location.Name = "Location";
            this.Location.ReadOnly = true;
            this.Location.Visible = false;
        }

        #endregion
        private System.Windows.Forms.DataGridViewTextBoxColumn Location;

解决方法

此警告特定于“设计器”代码。此问题的另一个示例是,如果(在设计器中)您尝试将网格列“名称”属性设置为“名称”。在这种情况下(在设计器代码中),编译器将在行 string 上抛出一个隐式转换为 this.Name = "Form1";. 异常。 ,而不是“forms.Name”属性。因此编译器会混淆。

您收到警告而不是转换错误的原因是因为您没有“更改”“表格”默认的“位置”属性。如果(在设计器中)您单击“FORM”并将其“Location”属性更改为 X=10、Y=10,那么当您编译代码时……您将得到如下所示的异常……

enter image description here

如前所述,编译器将 this.Location 视为 COLUMN,而不是表单 Location 属性。

换句话说,所有这些问题都来自“设计器”代码运行的“时间”以及将列命名为与表单属性名称相同的名称时的混淆。我将假设这是一个“错误”,因为对于“this”是“哪个”对象应该有明确的区别……但是,不难看出“为什么”存在一些混淆。

正如已经评论过的,您可以将列名称更改为其他名称……或者……您可以在表单的构造函数调用 InitializeComponent(); 方法后在代码中添加列。显然,在代码中,您不能在表单的构造函数调用 InitializeComponent(); 方法之前将列添加到网格中,但是,如果您在调用 InitializeComponent(); 方法之后“在代码中”添加列,例如表单 Load 事件或表单的构造函数中,然后它将按预期工作,而不会出现错误或警告。