c# - WPF项目的奇怪行为(类命名)

标签 c# wpf visual-studio-2010 class naming

尝试构建我的项目时遇到一个奇怪的错误 ExpertSystem在解决方案中ExpertSystem :

Error 1 The type name 'App' does not exist in the type 'ExpertSystem.ExpertSystem' D:\Users\Kirill\Documents\Visual Studio 2010\Projects\ExpertSystem\ExpertSystem\obj\x86\Debug\App.g.cs 60 26 ExpertSystem



我什至不知道 VS 在构建时会创建这个文件。所以,我开始在我最后一次编辑代码中搜索问题,发现问题出现在我的最后一个类中:
namespace ExpertSystem
{
    public class ExpertSystem
    {
    //...
    }
}

当类名更改为不同于 ExpertSystem 的名称时,项目编译没有错误。

谁能解释一下,我实际上可以在 C# 中拥有与命名空间/项目/解决方案同名的类吗?或者这是某种 VS/WPF 错误?

谢谢。

最佳答案

VS 为每个 XAML 文件生成部分类(不是在构建期间,而是在设计期间),以便(例如)将命名组件声明和填充为类字段。

如果您想轻松阅读设计器生成的 App.g.css 文件(与 App.xaml 和 App.xaml.cs 文件关联)的内容,请转到 App.xaml.cs 文件并执行“转到定义” "在类构造函数中的 InitializeComponent() 函数调用上。我不知道你身上潜伏着什么,但我希望设计师会产生这样的东西(也许不是这样,但问题是一样的):

var foo = (SystemExpert.App)(Application.Current)

应该理解为:
var foo = (global::SystemExpert.App)(Application.Current)

现在,如果您在 SystemExpert 程序集命名空间中创建一个 SystemExpert 类,并且 App 类也在 SystemExpert 命名空间中声明,编译器将理解:
var foo = (global::SystemExpert.SystemExpert.App)(Application.Current)
            ^^^^^^^^^^^^^^^^
         the current namespace

以与命名空间完全相同的方式命名一个类是不好的做法:它会使编译器感到困惑。

关于c# - WPF项目的奇怪行为(类命名),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5436295/

相关文章:

c# - 以编程方式在 IIS 中注册 Silverlight MIME 类型

c# - 样式化 RibbonComboBox 内容

wpf - 用于使用 WPF 选择多个文件的 OpenFileDialog

c++ - Visual Studio 2010 错误

c# - 在 C# 中使用 Uploadify

c# - CLR 中的托管堆

wpf - WPF 列表框的填充问题

c++ - 怎么可能知道是什么导致了异常

.net - 停止 .NET Firebird (2.6.5) 提供程序将所有 SQL 写入控制台

c# - SQL Server CE 3.5 SP1 存储过程