应用程序的入口函数是main函数,在Console程序和Winform程序main函数都有清晰的定义,能够很容易找到,可是WPF的工程文件中却找不到main函数的定义,是WPF不须要main函数吗?NO! NO! NO! 不要太天真了,WPF是有main函数的,VS帮咱们自动生成了,在obj\Debug\App.g.cs文件中能够看到如下的定义(obj\Debug文件夹下还有一个叫App.g.i.cs的文件,文件内容与App.g.cs一致,这个文件也是自动生成的,是为了VS的intelligence 智能感知服务的,关于intelligence 之后再讲)。app
能够看到Main函数在App类中定义,App类由VS自动生成,该类继承自System.Windows.Application,Application类维护了应用程序的生命周期,每一个运行中的WPF程序都由Application的一个实例表示。以上代码中关键的两句是:函数
this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);this
app.Run();orm
这两句的做用是启动应用程序,并将"MainWindow.xaml"定义的窗口做为该应用程序的主窗口。自动生成的代码比较简单,Application类能够作的事情远不止这些,之后能够详细讲一下。blog
以上是自动生成的Main函数,也能够手动建立咱们本身的Main函数,以下:继承
public class StartUp
{
[STAThread]
public static void Main(string[] args)
{
var app = new App
{
StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative)
};
app.Run();
}
}生命周期
可是你会获得以下的编译错误:ci
error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.string
缘由也很简单,VS帮你生成了一个Main函数,你又本身定义了一个Main函数,可是应用程序只能有一个入口,系统不知道要用哪个了,因此须要手动指定一个。在工程的属性的Application页中,设置Startup object为咱们刚刚定义的类StartUp就能够了。it