C#Windows窗体类型转换错误

本文关键字:错误 类型转换 窗体 C#Windows | 更新日期: 2023-09-27 18:01:10

现在,我正在从课本上学习C#。在我目前停留在Windows窗体这一章中的一个例子中,我被指示输入以下代码来创建一个简单的窗口:

namespace WinForms {
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
public class HelloWindowsForms : System.Windows.Forms.Form
{
    private System.Windows.Forms.Label label1;
    public HelloWindowsForms()
    {
        this.label1 = new System.Windows.Forms.Label();
        label1.Location = new System.Drawing.Point(8,8);
        label1.Text = "Hello Windows Forms!";
        label1.Size = new System.Drawing.Size(408,48);
        label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 24f);
        label1.TabIndex = 0;
        label1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; //this is the problem
        this.Text = "Hello World";
        this.MaximizeBox = false;
        this.AutoScaleBaseSize = new System.Drawing.Size(5,13);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MinimizeBox = false;
        this.ClientSize = new System.Drawing.Size(426,55);
        this.Controls.Add(label1);
    }
    public static void Main(string[] args)
    {
        Application.Run(new HelloWindowsForms());
    }
    }
}

在问题行(在单行注释中指定(上,我在运行此程序时收到以下错误:

Cannot implicitly convert type 'System.Windows.Forms.HorizontalAlignment' to 'System.Drawing.ContentAlignment'. An explicit conversion exists (are you missing a cast?) (CS0266)

网上的其他消息来源说我需要选角,但我不知道选什么或选什么。我试着跳过并完成这一章,但在尝试做所有示例时,我都会遇到类似的Cannot implicitly convert type错误。有人能帮我想办法解决这个问题吗?

C#Windows窗体类型转换错误

您使用了错误的枚举。当TextAlign属性正在调用System.Drawing.ContentAlignment枚举时,您正在使用System.Windows.Forms.HorizontalAlignment枚举。试试这个:

label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;

我遇到了同样的问题,并解决了这个问题,

如果您正在使用

标签

然后使用这个:

this.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;

我想你在用

文本框

因此,使用:

this.textbox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;