C#开发求助:“Font是命名空间却被当作类型使用”错误
解决“Font is a namespace but is used like a type”错误
你的推测完全正确——错误根源就是自定义的Font命名空间和.NET类库中System.Drawing.Font类重名,导致编译器无法区分你要引用的是哪个。以下是三种可行的修复方法:
方法一:重命名自定义命名空间
最简单的方式是把自己的命名空间改成不冲突的名称,比如MyFontApplication:
namespace MyFontApplication { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void fontFamily_MS_CheckedChanged(object sender, EventArgs e) { sampleText.Font = new Font("Microsoft Sans Serif"); } } }
方法二:使用完全限定名引用系统Font类
如果不想修改命名空间,就在创建Font对象时指定完整的命名空间路径,明确告诉编译器要使用系统的Font类:
namespace Font { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void fontFamily_MS_CheckedChanged(object sender, EventArgs e) { sampleText.Font = new System.Drawing.Font("Microsoft Sans Serif"); } } }
方法三:为系统Font类设置别名
在代码文件顶部给System.Drawing.Font定义一个别名,后续用别名来创建对象,避免命名冲突:
using SystemFont = System.Drawing.Font; namespace Font { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void fontFamily_MS_CheckedChanged(object sender, EventArgs e) { sampleText.Font = new SystemFont("Microsoft Sans Serif"); } } }
内容的提问来源于stack exchange,提问作者Rama
相关产品推荐
相关产品推荐

