CodeBehind和CodeFile的歷史故事

28 July 2011 — Written by Sky Chang
#ASP.NET#Visual Studio

今天晚上,我朋友丟了一個問題給我,問題內容大致上是這樣的:"我在網路上看到,大家都說CodeBehind是.net 1.1時代的東西,現在用CodeFile比較好,但為什麼VS2010的web application專案,自動建立出來的,都是CodeBehind??",聽完這個問題,我當下反應是愣了一下,因為完全沒想過這方面的事情啊XD,後來查了一下,也順便在這裡做個整理。

首先,的確,早期1.1是使用CodeBehind,到了2.0時期,出現了CodeFile,甚至到了.net 3.0時期微軟的MSDN也是建議換成CodeFile:

This attribute is included for compatibility with previous versions of ASP.NET, to implement the code-behind feature. In ASP.NET version 2.0, you should instead use the **CodeFile** attribute to specify the name of the source file, along with the **Inherits** attribute to specify the fully qualified name of the class. [http://msdn.microsoft.com/en-us/library/ydy4x04a%28VS.85%29.aspx](http://msdn.microsoft.com/en-us/library/ydy4x04a%28VS.85%29.aspx "http://msdn.microsoft.com/en-us/library/ydy4x04a%28VS.85%29.aspx")

而且,MSDN也有How To教學,教導大家如何更換: http://msdn.microsoft.com/zh-tw/library/ms227671%28VS.80%29.aspx

但是到了.net 3.5時代,那段建議就被拿掉了,取而代之的是: > CodeBehind

Specifies the name of the compiled file that contains the class associated with the page. This attribute is not used at run time. This attribute is used for Web application projects. The CodeFile attribute is used for Web site projects. For more information about Web project types in Visual Studio, see Web Application Projects versus Web Site Projects. > CodeFile

Specifies a path to the referenced code-behind file for the page. This attribute is used together with the Inherits attribute to associate a code-behind source file with a Web page. The attribute is valid only for compiled pages. This attribute is used for Web site projects. The CodeBehind attribute is used for Web application projects. For more information about Web project types in Visual Studio, see Web Application Projects versus Web Site Projects.

所以,其實在2.0~3.0這段期間,大家說要把CodeBehind改成CodeFile,其實也沒有錯,因為當初MS的確是這樣建議的,但是到了.net 3.5時期,MS就把這兩個區分出來,如上面文章所示,現在的CodeBehind是應用於Web application project裡面使用,也就是用於先編譯成dll的專案,而CodeFile則是使用於Web site project的專案,也就是傳上.cs檔案到Server,讓Server編譯,所以依據現在來看,CodeBehind已經不等於舊時代的產物了喔。

Sky & Study4.TW