ASP.NET WEB控制項命名低級錯誤一例

來源:互聯網
上載者:User

搞程式的人都知道變數的命名不要與語言關鍵字衝突,我今天還遇到一個ASP.NET WEB控制項命名帶來的問題,這個問題容易把人搞蒙。

我建立了一個名為“File.aspx”的頁面,並在字碼頁使用“File”類,按照常規操作,先在字碼頁頁頭匯入“System.IO”命名空間,結果在代碼本文發現File類點不出其常見的方法來,即使手動書寫一段正確的File類作業碼,都是無法編譯通過的,會報File類後面加的那個方法不包含在File類中,這段出錯的代碼如下:


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class File : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader sr = File.OpenText(Server.MapPath(".")+"\\Table.sql");
    }
}

細心的你也許已經發現問題所在了,就是此時出現了兩個File類,一個是System.IO.File,另一個則是建立WEB頁面的時候自動產生與檔案名稱同名的類public partial class File,此時就導致代碼本文StreamReader sr = File這裡的File類定義不明確了,此時在IDE中的自動提示顯示的是public partial class File類下面的成員,所以一開始說的問題就出現了。

知道問題出在那裡,解決辦法自然也就找到了。解決辦法之一就是要時刻提醒自己不要使建立的WEB分頁檔名與代碼中要使用的類重名,另外一個更科學的辦法就是使用命名空間全稱或命名空間別名,如下面那樣:


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class File : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader sr = System.IO.File.OpenText(Server.MapPath(".")+"\\Table.sql");
    }
}

這個問題顯然簡單,但是稍微粗心會使你認為是.NET架構出了問題或者是VS IDE出了問題,值得注意!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.